react-websocket 3.5.0 → 3.6.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/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"core.js","names":["VOLATILE"],"sources":["../src/types.ts","../src/client.ts","../src/latency.ts","../src/requests.ts","../src/responder.ts","../src/sendrate.ts","../src/state.ts","../src/topics.ts"],"sourcesContent":["/**\n * Where to connect: a URL, or a function that returns one (sync or async).\n *\n * A function is called before **every** connection attempt, including reconnects,\n * so it can put a fresh auth token in the URL. If it throws or rejects, that counts\n * as a failed attempt and is retried with backoff.\n *\n * @example\n * ```ts\n * createWebSocket(async () => `wss://api.example.com/live?token=${await getToken()}`);\n * ```\n */\nexport type UrlSource = string | (() => string | Promise<string>);\n\n/**\n * Connection state.\n *\n * - `idle`: not connected and not trying to be. Nobody is using the client yet, or everyone stopped.\n * - `connecting`: the first attempt is in progress.\n * - `open`: connected. `send()` goes out immediately.\n * - `reconnecting`: the connection dropped (or an attempt failed) and a retry is scheduled or in progress.\n * - `closed`: stopped for good, by `close()` or after giving up on reconnecting.\n * It stays closed until `connect()` or `reconnect()` is called, or every hook unmounts.\n */\nexport type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';\n\n/** The client's state as seen by React. A new object is created on every change. */\nexport interface Snapshot<In> {\n /** Connection state. */\n readonly status: Status;\n /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */\n readonly lastMessage: In | undefined;\n /** Consecutive failed attempts since the last successful open. `0` while open. */\n readonly attempt: number;\n}\n\n/** Details of a closed connection, from the browser's `CloseEvent`. */\nexport interface CloseInfo {\n /** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */\n readonly code: number;\n /** Close reason sent by the side that closed the connection. Often empty. */\n readonly reason: string;\n /** Whether the closing handshake completed. */\n readonly wasClean: boolean;\n}\n\n/** Anything `WebSocket.prototype.send` accepts: a string, `Blob`, `ArrayBuffer` or typed array. */\nexport type SendData = Parameters<WebSocket['send']>[0];\n\n/** Reconnect timing. Delay before attempt `n` = `min(maxDelay, minDelay * factor ** (n - 1))`, minus jitter. */\nexport interface ReconnectOptions {\n /**\n * Maximum consecutive reconnect attempts. When the last one fails too, the client\n * gives up: the status becomes `closed` and `ready` rejects. `0` never retries.\n * @default Infinity\n */\n maxAttempts?: number;\n /**\n * Delay before the first retry, in ms.\n * @default 1000\n */\n minDelay?: number;\n /**\n * Upper bound for the delay, in ms.\n * @default 30000\n */\n maxDelay?: number;\n /**\n * Backoff multiplier applied per attempt.\n * @default 2\n */\n factor?: number;\n /**\n * Randomly shave up to this fraction (0–1) off each delay, so that many clients\n * dropped at once don't all reconnect at the same moment.\n * @default 0.5\n */\n jitter?: number;\n /**\n * Called on every unexpected close. Return `false` to stop reconnecting.\n *\n * @example\n * ```ts\n * // Don't retry when the server rejects our credentials.\n * shouldReconnect: close => close.code !== 4001\n * ```\n * @default () => true\n */\n shouldReconnect?: (close: CloseInfo) => boolean;\n}\n\n/** Application-level keep-alive. Useful behind proxies that drop idle connections. */\nexport interface HeartbeatOptions {\n /** Send `message` every `interval` ms while open. */\n interval: number;\n /**\n * Sent as-is (it is not passed through `serialize` or `json`).\n * @default 'ping'\n */\n message?: string;\n /** Incoming data equal to this string is swallowed instead of being delivered as a message. */\n pong?: string;\n /**\n * If nothing at all arrives within this many ms after a ping, the connection is\n * treated as dead: it closes with code `4000` and reconnects.\n */\n timeout?: number;\n}\n\n/** Per-message options for `send()`. */\nexport interface SendOptions {\n /**\n * Drop the message instead of queueing it when the socket isn't open. For data that\n * is stale by the time a reconnect finishes, such as player input or cursor positions.\n * @default false\n */\n volatile?: boolean;\n /**\n * Keep only the newest queued message with this key. Sending again with the same key\n * while disconnected replaces the earlier one, which moves to the back of the queue\n * (or of the `priority` messages, for a priority one).\n * For state where only the latest value matters, such as \"my position is now (x, y)\".\n */\n key?: string;\n /**\n * Queue this message ahead of every message queued without `priority`, after earlier\n * priority messages. For control messages that must not wait behind a backlog, such as\n * cancel, interrupt or a token refresh. Messages sent from `open` listeners still go first.\n *\n * It only matters while the socket isn't open: once a message is handed to the browser,\n * nothing can overtake it. To keep that buffer short, send bulky streams with `maxBuffered`.\n * @default false\n */\n priority?: boolean;\n /**\n * Drop the message instead of sending it while more than this many bytes are already\n * waiting in the browser's send buffer (`socket.bufferedAmount`). For high-rate streams on\n * a slow link, such as audio frames or per-tick input, where a late message is worse than\n * none. `send()` returns `false`, and `onDrop` isn't called.\n *\n * Only checked while the socket is open: a message queued while disconnected is sent on\n * open regardless. `bufferedAmount` includes what you sent earlier in the same task, so set\n * it well above one burst of messages.\n *\n * @example\n * ```ts\n * voice.send(frame, { volatile: true, maxBuffered: 64 * 1024 });\n * ```\n */\n maxBuffered?: number;\n /**\n * Called if the message is dropped from the queue without being sent: replaced by a\n * newer message with the same `key`, or evicted by `queue.limit`. Not called when the\n * queue is cleared because the client closed or gave up, or when `send()` drops the\n * message right away (`volatile` while not open, or `maxBuffered`) and returns `false`.\n */\n onDrop?: () => void;\n}\n\n/** Bounds for the send queue. */\nexport interface QueueOptions {\n /**\n * Maximum number of messages held while not connected. When full, the oldest\n * message is dropped, skipping `priority` messages unless nothing else is queued.\n * @default Infinity\n */\n limit?: number;\n}\n\n/**\n * The minimal [Standard Schema v1](https://standardschema.dev) interface, implemented\n * by zod (3.24+), valibot (1.0+), arktype (2.0+) and others. You don't need to\n * import this; pass your schema object directly.\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n };\n}\n\n/** The result of a Standard Schema `validate` call. */\nexport type StandardSchemaResult<Output> =\n | { readonly value: Output; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<{ readonly message: string }> };\n\n/**\n * Connection options, shared by `createWebSocket(url, options)` and `useWebSocket(url, options)`.\n *\n * @typeParam In - Type of incoming messages (after `parse`/`json`/`schema`).\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketOptions<In = unknown, Out = unknown> {\n /** Sub-protocol(s) passed to the `WebSocket` constructor. */\n protocols?: string | string[];\n /**\n * How binary messages are exposed.\n * @default 'blob'\n */\n binaryType?: BinaryType;\n /**\n * `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail\n * to parse are reported to `onError` as a {@link MessageError} and not delivered.\n * @default false\n */\n json?: boolean;\n /**\n * Custom decoder for incoming `event.data`. Takes precedence over `json`.\n * Throwing reports a {@link MessageError} and drops the message.\n */\n parse?: (data: unknown) => unknown;\n /** Custom encoder for outgoing messages. Takes precedence over `json`. */\n serialize?: (message: Out) => SendData;\n /**\n * Validate incoming messages (after parsing) with any Standard Schema library.\n * Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.\n * The message type `In` is inferred from it.\n *\n * @example\n * ```ts\n * createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });\n * ```\n */\n schema?: StandardSchemaV1<unknown, In>;\n /**\n * Reconnect with exponential backoff after an unexpected close. `false` disables it.\n * @default true\n */\n reconnect?: boolean | ReconnectOptions;\n /** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */\n heartbeat?: HeartbeatOptions;\n /**\n * Buffer `send()` calls made while not connected and send them, in order, on open\n * (right after `open` listeners run).\n * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.\n * The queue is cleared by `close()` or when the client gives up.\n * @default true\n */\n queue?: boolean | QueueOptions;\n /**\n * Receives debug messages about connection attempts, retries and dropped messages.\n * @example\n * ```ts\n * logger: console.debug\n * ```\n */\n logger?: (message: string, ...details: unknown[]) => void;\n /**\n * `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.\n * When omitted, the global `WebSocket` is used in browsers. During a server render\n * (no `window`), nothing connects unless an implementation is passed.\n */\n WebSocket?: typeof WebSocket;\n}\n\n/**\n * Reported via the `error` event (and `onError`) when an incoming message can't be\n * decoded by `parse`/`json` or fails `schema` validation. The message is not delivered.\n *\n * @example\n * ```ts\n * onError(error) {\n * if (error instanceof MessageError) report(error.data, error.issues);\n * }\n * ```\n */\nexport class MessageError extends Error {\n /** The raw `event.data` that failed. */\n readonly data: unknown;\n /** Schema validation issues, when the message failed `schema`. */\n readonly issues: ReadonlyArray<{ readonly message: string }> | undefined;\n\n constructor(\n message: string,\n data: unknown,\n options?: { cause?: unknown; issues?: ReadonlyArray<{ readonly message: string }> }\n ) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'MessageError';\n this.data = data;\n this.issues = options?.issues;\n }\n}\n\n/** Events emitted by a client. Subscribe with `client.on(type, listener)` or `useWebSocketEvent`. */\nexport interface EventMap<In> {\n /**\n * The socket opened (initially or after a reconnect). Listeners run before queued\n * messages are sent, so a handshake sent from here goes out first.\n */\n open: (event: Event) => void;\n /** A message arrived and passed `parse` and `schema`. */\n message: (message: In, event: MessageEvent) => void;\n /** A socket closed, whether it will be retried or not. */\n close: (close: CloseInfo) => void;\n /**\n * A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,\n * or the `Error` thrown by the `WebSocket` constructor or a `url` function.\n */\n error: (error: Event | MessageError | Error) => void;\n}\n\n/**\n * A WebSocket connection that reconnects, queues, decodes and can be shared.\n * Create one with `createWebSocket()`.\n *\n * The connection is reference-counted: it opens when the first hook mounts (or\n * `ready` is read) and closes one tick after the last hook unmounts. Calling\n * `connect()` keeps it open regardless, until `close()`.\n *\n * @typeParam In - Type of incoming messages.\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketClient<In = unknown, Out = unknown> {\n /** The URL (or URL function) the client was created with. */\n readonly url: UrlSource;\n /**\n * A promise that resolves once the socket has opened. Reading it starts an idle client.\n *\n * It stays resolved through automatic reconnects, so `use(client.ready)` shows a\n * Suspense fallback only for the first connection, never on a network blip; use\n * `status` to show reconnects. It rejects when the client gives up reconnecting, when\n * `close()` is called, and during a server render. After that, `connect()` or\n * `reconnect()` make it a new pending promise.\n *\n * It is safe to pass to React 19's `use()`: the same promise is returned until its state\n * changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is\n * already settled.\n */\n readonly ready: Promise<void>;\n /** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */\n readonly socket: WebSocket | null;\n /** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** The current {@link Snapshot}. Returns the same object until something changes. */\n getSnapshot(): Snapshot<In>;\n /**\n * Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown\n * asynchronously, so one failing listener doesn't break the others.\n */\n on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;\n /**\n * Send a message (encoded with `serialize`/`json` if configured). If the socket isn't\n * open, the message is queued and sent on open (see the `queue` option), unless\n * `options.volatile` is set.\n * @returns `true` if it was sent immediately, `false` if it was queued or dropped\n * (`volatile` while not open, or `maxBuffered` while open).\n *\n * @example\n * ```ts\n * game.send({ type: 'input', dx, dy }, { volatile: true }); // never replayed after a reconnect\n * game.send({ type: 'position', x, y }, { key: 'position' }); // only the newest is queued\n * game.send({ type: 'leave' }, { priority: true }); // ahead of everything already queued\n * ```\n */\n send(message: Out, options?: SendOptions): boolean;\n /**\n * Start connecting, and keep the connection open even when no hook is using the\n * client, until `close()` is called. Does nothing if already connecting or open.\n */\n connect(): void;\n /**\n * Close the connection and stop reconnecting. The status becomes `closed` and the\n * send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`\n * to start again.\n * @param code - Close code. @default 1000\n */\n close(code?: number, reason?: string): void;\n /**\n * Drop the current socket (if any) and connect again immediately, resetting the\n * backoff. Also restarts a `closed` client.\n */\n reconnect(): void;\n /**\n * Hold the connection open until the returned function is called. This is what the\n * hooks use; call it yourself to integrate with non-React code.\n * @returns A release function (safe to call more than once).\n */\n acquire(): () => void;\n}\n","import {\n MessageError,\n type CloseInfo,\n type EventMap,\n type ReconnectOptions,\n type SendData,\n type SendOptions,\n type Snapshot,\n type StandardSchemaResult,\n type UrlSource,\n type WebSocketClient,\n type WebSocketOptions\n} from './types';\n\nconst OPEN = 1;\n\nconst RECONNECT_DEFAULTS = {\n maxAttempts: Infinity,\n minDelay: 1000,\n maxDelay: 30_000,\n factor: 2,\n jitter: 0.5\n} satisfies ReconnectOptions;\n\ntype Timer = ReturnType<typeof setTimeout> | undefined;\n\n// How long a connection opened only by reading `ready` waits for a holder before closing.\n// Long enough for React to retry a suspended render and commit its hooks.\nconst READY_GRACE = 5000;\n\n// React's `use()` reads `status`/`value`/`reason` off a thenable to skip suspending\n// when it is already settled.\ntype TrackedPromise = Promise<void> & {\n status: 'pending' | 'fulfilled' | 'rejected';\n value?: void;\n reason?: unknown;\n};\n\ninterface Deferred {\n readonly promise: TrackedPromise;\n settled: boolean;\n resolve(): void;\n reject(reason: unknown): void;\n}\n\nfunction createDeferred(): Deferred {\n let resolve!: () => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<void>((res, rej) => {\n resolve = res;\n reject = rej;\n }) as TrackedPromise;\n promise.status = 'pending';\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n promise.catch(() => {});\n const deferred: Deferred = {\n promise,\n settled: false,\n resolve() {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'fulfilled';\n promise.value = undefined;\n resolve();\n },\n reject(reason) {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'rejected';\n promise.reason = reason;\n reject(reason);\n }\n };\n return deferred;\n}\n\nfunction rethrowAsync(error: unknown) {\n queueMicrotask(() => {\n throw error;\n });\n}\n\nfunction isThenable<T>(value: unknown): value is PromiseLike<T> {\n return typeof (value as PromiseLike<T> | null)?.then === 'function';\n}\n\n/**\n * @internal Option key for a callback run when the client tears down, which lets the hooks'\n * URL registry forget clients nobody holds anymore. A registered symbol rather than an export,\n * because the hooks entry imports the client from the `core` entry at runtime.\n */\nconst ON_TEARDOWN = Symbol.for('react-websocket.onTeardown');\n\nfunction createClient<In = unknown, Out = unknown>(\n url: UrlSource,\n options: WebSocketOptions<In, Out> & { [ON_TEARDOWN]?: () => void } = {}\n): WebSocketClient<In, Out> {\n const onTeardown = options[ON_TEARDOWN];\n const log = options.logger ?? (() => {});\n const retry =\n options.reconnect === false\n ? null\n : {\n ...RECONNECT_DEFAULTS,\n ...(typeof options.reconnect === 'object' ? options.reconnect : {})\n };\n const queueLimit =\n options.queue === false\n ? 0\n : typeof options.queue === 'object'\n ? Math.max(0, options.queue.limit ?? Infinity)\n : Infinity;\n\n let snapshot: Snapshot<In> = { status: 'idle', lastMessage: undefined, attempt: 0 };\n const storeListeners = new Set<() => void>();\n const listeners: { [K in keyof EventMap<In>]: Set<EventMap<In>[K]> } = {\n open: new Set(),\n message: new Set(),\n close: new Set(),\n error: new Set()\n };\n\n let ws: WebSocket | null = null;\n let wanted = false;\n let refs = 0;\n // Set by a public `connect()`: stay connected after the last hook releases, until `close()`.\n let pinned = false;\n // Priority messages form the head of the queue, in the order they were sent.\n let pending: {\n data: SendData;\n key: string | undefined;\n priority: boolean | undefined;\n onDrop: (() => void) | undefined;\n }[] = [];\n let ready: Deferred | null = null;\n // Opened at least once since the client was last started. `ready` stays resolved through\n // automatic reconnects so `use(client.ready)` doesn't swap content for a fallback on every blip.\n let opened = false;\n let unavailable: Deferred | null = null;\n let startScheduled = false;\n let inbox: Promise<void> | null = null;\n // Bumped per connection attempt so a slow `url()` can't resurrect a cancelled one.\n let generation = 0;\n let windowBound = false;\n let retryTimer: Timer;\n let teardownTimer: Timer;\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n let pongTimer: Timer;\n\n function set(patch: Partial<Snapshot<In>>) {\n snapshot = { ...snapshot, ...patch };\n for (const listener of [...storeListeners]) {\n try {\n listener();\n } catch (error) {\n rethrowAsync(error);\n }\n }\n }\n\n function emit<K extends keyof EventMap<In>>(type: K, ...args: Parameters<EventMap<In>[K]>) {\n for (const listener of [...listeners[type]]) {\n try {\n (listener as (...a: Parameters<EventMap<In>[K]>) => void)(...args);\n } catch (error) {\n rethrowAsync(error);\n }\n }\n }\n\n function getImpl(): typeof WebSocket | undefined {\n if (options.WebSocket) return options.WebSocket;\n // Node has a global WebSocket too; don't connect from a server render.\n return typeof window === 'undefined' ? undefined : globalThis.WebSocket;\n }\n\n function rejectReady(reason: unknown) {\n if (!ready || ready.settled) ready = createDeferred();\n ready.reject(reason);\n }\n\n function retryNow() {\n if (retryTimer !== undefined) {\n log('network or visibility change, retrying now');\n open();\n }\n }\n\n function onVisibilityChange() {\n if (document.visibilityState === 'visible') retryNow();\n }\n\n function bindWindow() {\n if (windowBound || typeof window === 'undefined') return;\n windowBound = true;\n window.addEventListener('online', retryNow);\n document.addEventListener('visibilitychange', onVisibilityChange);\n }\n\n function unbindWindow() {\n if (!windowBound) return;\n windowBound = false;\n window.removeEventListener('online', retryNow);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n }\n\n function startHeartbeat(socket: WebSocket) {\n const heartbeat = options.heartbeat;\n if (!heartbeat) return;\n heartbeatTimer = setInterval(() => {\n socket.send(heartbeat.message ?? 'ping');\n if (heartbeat.timeout && pongTimer === undefined) {\n pongTimer = setTimeout(() => {\n log('heartbeat timeout');\n // The close handshake may never finish on a dead link, so don't wait for it.\n detach(socket, false);\n socket.close(4000, 'heartbeat timeout');\n handleClose({ code: 4000, reason: 'heartbeat timeout', wasClean: false });\n }, heartbeat.timeout);\n }\n }, heartbeat.interval);\n }\n\n function stopHeartbeat() {\n clearInterval(heartbeatTimer);\n clearTimeout(pongTimer);\n heartbeatTimer = pongTimer = undefined;\n }\n\n /** Stop tracking `socket`. Its eventual close event is still reported unless `reportClose` is false. */\n function detach(socket: WebSocket, reportClose: boolean) {\n if (ws === socket) ws = null;\n socket.onopen = socket.onmessage = socket.onerror = null;\n socket.onclose = reportClose\n ? event => emit('close', { code: event.code, reason: event.reason, wasClean: event.wasClean })\n : null;\n }\n\n function backoff(attempt: number) {\n const { minDelay, maxDelay, factor, jitter } = retry!;\n const base = Math.min(maxDelay, minDelay * factor ** (attempt - 1));\n return Math.round(base * (1 - jitter * Math.random()));\n }\n\n function open() {\n clearTimeout(retryTimer);\n retryTimer = undefined;\n const Impl = getImpl();\n if (!Impl) return;\n const id = ++generation;\n set({ status: snapshot.attempt === 0 ? 'connecting' : 'reconnecting' });\n\n let target: string | Promise<string>;\n try {\n target = typeof url === 'string' ? url : url();\n } catch (error) {\n urlFailed(error);\n return;\n }\n if (typeof target === 'string') {\n start(Impl, target);\n return;\n }\n Promise.resolve(target).then(\n resolved => {\n if (id === generation && wanted) start(Impl, resolved);\n },\n error => {\n if (id === generation && wanted) urlFailed(error);\n }\n );\n }\n\n /** `url()` threw or rejected (e.g. a token refresh failed): count it as a failed attempt. */\n function urlFailed(error: unknown) {\n const reason = error instanceof Error ? error : new Error(String(error));\n log('url() failed', reason);\n emit('error', reason);\n retryOrFail({ code: 1006, reason: 'url() failed', wasClean: false }, reason);\n }\n\n function start(Impl: typeof WebSocket, target: string) {\n let socket: WebSocket;\n try {\n socket = new Impl(target, options.protocols);\n } catch (error) {\n // e.g. an invalid URL; retrying won't help.\n emit('error', error as Error);\n fail(error);\n return;\n }\n if (options.binaryType) socket.binaryType = options.binaryType;\n ws = socket;\n log('connecting', target);\n\n socket.onopen = event => {\n log('open');\n opened = true;\n set({ status: 'open', attempt: 0 });\n startHeartbeat(socket);\n ready?.resolve();\n // Nobody holds it (it was started by reading `ready`, or the last holder left while\n // connecting): close it unless a holder turns up soon.\n if (refs === 0 && !pinned) {\n clearTimeout(teardownTimer);\n teardownTimer = setTimeout(teardown, READY_GRACE);\n }\n // `open` listeners go first, so a handshake sent from `onOpen` (e.g. auth) precedes\n // whatever was queued while disconnected.\n emit('open', event);\n if (ws !== socket) return; // a listener closed or replaced it\n const queued = pending;\n pending = [];\n for (const { data } of queued) socket.send(data);\n };\n socket.onmessage = event => receive(event, socket);\n socket.onerror = event => emit('error', event);\n socket.onclose = event => {\n detach(socket, false);\n handleClose({ code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function handleClose(info: CloseInfo) {\n stopHeartbeat();\n log('closed', info);\n retryOrFail(info);\n emit('close', info);\n }\n\n function retryOrFail(info: CloseInfo, error?: Error) {\n if (\n wanted &&\n retry &&\n snapshot.attempt < retry.maxAttempts &&\n (retry.shouldReconnect?.(info) ?? true)\n ) {\n const attempt = snapshot.attempt + 1;\n const delay = backoff(attempt);\n set({ status: 'reconnecting', attempt });\n log(`reconnecting in ${delay}ms (attempt ${attempt})`);\n retryTimer = setTimeout(open, delay);\n } else {\n fail(\n error ??\n new Error(`WebSocket closed (code ${info.code}${info.reason ? `: ${info.reason}` : ''})`)\n );\n }\n }\n\n function fail(reason: unknown) {\n wanted = false;\n opened = false;\n unbindWindow();\n pending = [];\n set({ status: 'closed' });\n rejectReady(reason);\n }\n\n function receive(event: MessageEvent, socket: WebSocket) {\n clearTimeout(pongTimer);\n pongTimer = undefined;\n if (options.heartbeat?.pong !== undefined && event.data === options.heartbeat.pong) return;\n\n // Async schema validation must not reorder messages.\n const run = () => decode(event, socket);\n if (inbox) {\n // One failed delivery must not stop the chain, or every later message is dropped.\n const next: Promise<void> = inbox\n .then(run)\n .catch(rethrowAsync)\n .then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n return;\n }\n const result = run();\n if (result) {\n const next: Promise<void> = result.catch(rethrowAsync).then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n }\n }\n\n function decode(event: MessageEvent, socket: WebSocket): void | Promise<void> {\n let value: unknown;\n try {\n value = options.parse\n ? options.parse(event.data)\n : options.json\n ? JSON.parse(event.data as string)\n : event.data;\n } catch (cause) {\n emit('error', new MessageError('Failed to parse message', event.data, { cause }));\n return;\n }\n\n const schema = options.schema;\n if (!schema) return deliver(value as In, event, socket);\n\n let result: ReturnType<(typeof schema)['~standard']['validate']>;\n try {\n result = schema['~standard'].validate(value);\n } catch (cause) {\n emit('error', new MessageError('Schema validation threw', event.data, { cause }));\n return;\n }\n if (isThenable<StandardSchemaResult<In>>(result)) {\n return Promise.resolve(result).then(\n r => validated(r, event, socket),\n cause => emit('error', new MessageError('Schema validation threw', event.data, { cause }))\n );\n }\n validated(result, event, socket);\n }\n\n function validated(result: StandardSchemaResult<In>, event: MessageEvent, socket: WebSocket) {\n if (result.issues) {\n emit(\n 'error',\n new MessageError('Message failed schema validation', event.data, { issues: result.issues })\n );\n } else {\n deliver(result.value, event, socket);\n }\n }\n\n function deliver(message: In, event: MessageEvent, socket: WebSocket) {\n if (ws !== socket) return; // closed or replaced while validating\n set({ lastMessage: message });\n emit('message', message, event);\n }\n\n function send(message: Out, sendOptions: SendOptions = {}): boolean {\n const data = options.serialize\n ? options.serialize(message)\n : options.json\n ? JSON.stringify(message)\n : (message as SendData);\n const { key, priority, maxBuffered } = sendOptions;\n if (ws && ws.readyState === OPEN) {\n // A late frame is worse than none: let a congested buffer drain instead of growing it.\n if (maxBuffered !== undefined && ws.bufferedAmount > maxBuffered) {\n log('dropped message: send buffer above maxBuffered');\n return false;\n }\n ws.send(data);\n return true;\n }\n if (queueLimit === 0 || sendOptions.volatile) {\n log('dropped message: socket is not open');\n return false;\n }\n if (!getImpl()) {\n // e.g. during a server render: this client can never connect, so don't hold on to it.\n log('dropped message: no WebSocket implementation available');\n return false;\n }\n if (key !== undefined) {\n pending = pending.filter(entry => {\n if (entry.key !== key) return true;\n dropped(entry);\n return false;\n });\n }\n let head = pending.findIndex(entry => !entry.priority);\n if (head < 0) head = pending.length;\n const entry = { data, key, priority, onDrop: sendOptions.onDrop };\n if (priority) pending.splice(head++, 0, entry);\n else pending.push(entry);\n if (pending.length > queueLimit) {\n // The oldest ordinary message goes first; priority ones only when nothing else is left.\n dropped(pending.splice(head < pending.length ? head : 0, 1)[0]!);\n log(`dropped oldest queued message: queue limit (${queueLimit}) reached`);\n }\n return false;\n }\n\n function dropped(entry: (typeof pending)[number]) {\n try {\n entry.onDrop?.();\n } catch (error) {\n rethrowAsync(error);\n }\n }\n\n function begin() {\n wanted = true;\n // Starting over after `close()` or giving up: wait for a new connection.\n if (snapshot.status === 'idle' || snapshot.status === 'closed') {\n opened = false;\n if (ready?.settled) ready = null;\n }\n snapshot = { ...snapshot, attempt: 0 }; // open() notifies\n bindWindow();\n open();\n }\n\n /** Start connecting unless already wanted. Used by holders (`acquire`, `ready`). */\n function ensureConnecting() {\n if (wanted || !getImpl()) return;\n begin();\n }\n\n function connect() {\n pinned = true;\n ensureConnecting();\n }\n\n function stop(code?: number, reason?: string) {\n wanted = false;\n generation++;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n unbindWindow();\n pending = [];\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(code, reason);\n }\n }\n\n function close(code = 1000, reason?: string) {\n pinned = false;\n opened = false;\n stop(code, reason);\n set({ status: 'closed', attempt: 0 });\n rejectReady(new Error('WebSocket was closed'));\n }\n\n function reconnect() {\n if (!getImpl()) return;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(1000, 'reconnect');\n }\n begin();\n }\n\n function teardown() {\n if (refs > 0 || pinned) return;\n // Someone may be suspended on `ready`; let the attempt finish.\n if (ready && !ready.settled) return;\n stop();\n ready = null;\n opened = false;\n set({ status: 'idle', attempt: 0 });\n onTeardown?.();\n }\n\n function acquire() {\n refs++;\n clearTimeout(teardownTimer);\n if (snapshot.status === 'idle') ensureConnecting();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--refs > 0) return;\n // Deferred so StrictMode's unmount/remount and route transitions don't churn the socket.\n clearTimeout(teardownTimer);\n teardownTimer = setTimeout(teardown, 0);\n };\n }\n\n return {\n url,\n get ready() {\n if (!getImpl()) {\n if (!unavailable) {\n unavailable = createDeferred();\n unavailable.reject(\n new Error('react-websocket: no WebSocket available here (server render?)')\n );\n }\n return unavailable.promise;\n }\n if (snapshot.status === 'idle' && !startScheduled) {\n // `ready` is read during render; start outside of it.\n startScheduled = true;\n queueMicrotask(() => {\n startScheduled = false;\n if (snapshot.status === 'idle') ensureConnecting();\n });\n }\n if (!ready) {\n ready = createDeferred();\n if (opened) ready.resolve();\n }\n return ready.promise;\n },\n get socket() {\n return ws;\n },\n subscribe(listener) {\n storeListeners.add(listener);\n return () => {\n storeListeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n on(type, listener) {\n // Wrap so the same function can be subscribed twice and unsubscribed independently.\n const entry = ((...args: unknown[]) =>\n (listener as (...a: unknown[]) => void)(...args)) as typeof listener;\n listeners[type].add(entry);\n return () => {\n listeners[type].delete(entry);\n };\n },\n send,\n connect,\n close,\n reconnect,\n acquire\n };\n}\n\n/**\n * Create a WebSocket client, usually at module level, to share across components.\n *\n * Nothing connects until a hook uses it, `ready` is read, or `connect()` is called.\n * It closes one tick after the last hook unmounts, unless `connect()` was called.\n *\n * @param url - A URL, or a function (sync or async) called before every connection\n * attempt, e.g. to put a fresh auth token in the URL on each reconnect.\n * @typeParam In - Type of incoming messages. Inferred from `options.schema` if given.\n * @typeParam Out - Type accepted by `send()`.\n *\n * @example\n * ```ts\n * type ChatIn = { user: string; text: string };\n * type ChatOut = { text: string };\n *\n * export const chat = createWebSocket<ChatIn, ChatOut>('wss://api.example.com/chat', { json: true });\n * ```\n */\nexport function createWebSocket<In = unknown, Out = unknown>(\n url: UrlSource,\n options?: WebSocketOptions<In, Out>\n): WebSocketClient<In, Out> {\n return createClient(url, options);\n}\n","import type { WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketLatency}: how pings and pongs look on the wire. */\nexport interface WebSocketLatencyOptions<In, Out> {\n /** The ping message, tagged with `id`. Sent with `volatile`, so pings are never queued. */\n ping: (id: number) => Out;\n /**\n * Recognize a pong: return the `id` of the ping it answers, and the server's clock\n * (`Date.now()` on the server, in ms) when it replied. Return `undefined` (or `null`)\n * for any other message. Without `time`, only the round-trip time is measured.\n */\n pong: (message: In) => { id: number | string; time?: number } | null | undefined;\n /**\n * How often to ping while open, in ms. The first ping goes out as soon as the socket opens.\n * @default 2000\n */\n interval?: number;\n /**\n * How many recent measurements to keep. `rtt` is their median, and `offset` comes from\n * the one with the lowest round trip, the most accurate estimate.\n * @default 5\n */\n samples?: number;\n}\n\n/** Latest latency measurements. A new object is created on every change. */\nexport interface Latency {\n /** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */\n readonly rtt: number | undefined;\n /**\n * Estimated server clock minus local clock, in ms. Add it to `Date.now()` for server time.\n * `undefined` until a pong carries `time`.\n */\n readonly offset: number | undefined;\n}\n\n/** Round-trip time and server clock offset for one client. Create with {@link createWebSocketLatency}. */\nexport interface WebSocketLatency {\n /** The client being measured. Hooks reading the latency keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /** The current {@link Latency}. Returns the same object until it changes. */\n getSnapshot(): Latency;\n /** Called whenever a measurement changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** The estimated server time: `Date.now() + offset`, or `Date.now()` before any estimate. */\n serverNow(): number;\n /** Ping now instead of waiting for the next interval. Does nothing unless the socket is open. */\n ping(): void;\n /** Stop pinging and listening. Only needed for instances created dynamically. */\n dispose(): void;\n}\n\nconst EMPTY: Latency = Object.freeze({ rtt: undefined, offset: undefined });\n\nfunction median(values: number[]) {\n const sorted = [...values].sort((a, b) => a - b);\n const middle = sorted.length >> 1;\n return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;\n}\n\n/**\n * Measure round-trip time and estimate the server's clock, for ping displays, countdowns\n * and timestamps that must agree across players.\n *\n * Pings are sent on an interval while the socket is open, and paused otherwise. Measurements\n * from a previous connection are discarded on reconnect, but the last values stay readable\n * until new ones arrive. It doesn't open the connection by itself.\n *\n * Pongs are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * export const latency = createWebSocketLatency(game, {\n * ping: id => ({ type: 'ping', id }),\n * pong: message => (message.type === 'pong' ? { id: message.id, time: message.time } : undefined)\n * });\n *\n * // In a component:\n * const { rtt } = useWebSocketLatency(latency);\n *\n * // Anywhere: seconds left in a round that ends at the server's `endsAt`.\n * const left = (endsAt - latency.serverNow()) / 1000;\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only, and keep literals such as\n// `type: 'ping'` from widening to `string` inside the callbacks.\nexport function createWebSocketLatency<In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>\n): WebSocketLatency {\n const interval = options.interval ?? 2000;\n const keep = Math.max(1, options.samples ?? 5);\n const listeners = new Set<() => void>();\n let snapshot = EMPTY;\n // Ping id -> `performance.now()` when sent. Pongs that never come are evicted oldest first.\n const inFlight = new Map<string, number>();\n let samples: { rtt: number; offset: number | undefined }[] = [];\n let nextId = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n\n function ping() {\n if (client.getSnapshot().status !== 'open') return;\n const id = ++nextId;\n inFlight.set(String(id), performance.now());\n if (inFlight.size > keep * 2) inFlight.delete(inFlight.keys().next().value!);\n client.send(options.ping(id), { volatile: true });\n }\n\n function start() {\n stop();\n inFlight.clear();\n samples = [];\n ping();\n timer = setInterval(ping, interval);\n }\n\n function stop() {\n clearInterval(timer);\n timer = undefined;\n }\n\n function measure(id: string, serverTime: number | undefined) {\n const sentAt = inFlight.get(id);\n if (sentAt === undefined) return;\n inFlight.delete(id);\n const rtt = performance.now() - sentAt;\n // The server read its clock about halfway through the round trip.\n const offset = serverTime === undefined ? undefined : serverTime + rtt / 2 - Date.now();\n samples.push({ rtt, offset });\n if (samples.length > keep) samples.shift();\n\n let best: (typeof samples)[number] | undefined;\n for (const sample of samples) {\n if (sample.offset !== undefined && (!best || sample.rtt < best.rtt)) best = sample;\n }\n snapshot = {\n rtt: median(samples.map(sample => sample.rtt)),\n offset: best ? best.offset : snapshot.offset\n };\n for (const listener of [...listeners]) listener();\n }\n\n const offs = [\n client.on('open', start),\n client.on('message', message => {\n const pong = options.pong(message);\n if (pong != null) measure(String(pong.id), pong.time);\n }),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') stop();\n })\n ];\n if (client.getSnapshot().status === 'open') start();\n\n return {\n client,\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n serverNow: () => Date.now() + (snapshot.offset ?? 0),\n ping,\n dispose() {\n stop();\n offs.forEach(off => off());\n }\n };\n}\n","import type { SendOptions, WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketRequests}: how requests and replies look on the wire. */\nexport interface WebSocketRequestsOptions<Req, In, Out> {\n /**\n * Build the outgoing message for `request(message)`, tagged with `id`. Annotate `message`\n * to type what `request()` accepts.\n */\n send: (message: Req, id: number) => Out;\n /**\n * The id an incoming message replies to, or `undefined` (or `null`) if it isn't a reply.\n * A string id matches the number it was sent as, so either echo works.\n */\n reply: (message: In) => number | string | null | undefined;\n /**\n * Called on a reply. Return something other than `undefined` to reject the request with\n * it instead of resolving, e.g. for a server-side error reply.\n */\n error?: (message: In) => unknown;\n /**\n * Default time to wait for a reply, in ms. `Infinity` waits forever.\n * @default 10000\n */\n timeout?: number;\n}\n\n/** Per-call options for {@link WebSocketRequests.request}. */\nexport interface RequestOptions extends SendOptions {\n /** Time to wait for a reply, in ms. Overrides the manager's `timeout`. */\n timeout?: number;\n /** Abort the request. It rejects with `signal.reason`. A late reply is ignored. */\n signal?: AbortSignal;\n}\n\n/** Request/response over one client. Create with {@link createWebSocketRequests}. */\nexport interface WebSocketRequests<Req, In> {\n /** The client requests are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Send a request and resolve with its reply. Holds the connection until it settles.\n *\n * Rejects with a `TimeoutError` `DOMException` after `timeout`, with `signal.reason` when\n * aborted, and with an `Error` when the connection it was sent on closes (the reply can\n * no longer arrive) or the client stops. A request made while disconnected is queued like\n * any other message and waits for the connection; it rejects if it is dropped from the\n * queue (replaced by a newer request with the same `key`, or evicted by `queue.limit`).\n */\n request(message: Req, options?: RequestOptions): Promise<In>;\n /** Number of requests waiting for a reply. */\n pending(): number;\n /** Reject every pending request and stop listening. Only needed for managers created dynamically. */\n dispose(): void;\n}\n\n// Last id sent per client, shared by its managers so two of them never send the same id\n// and resolve each other's requests with one reply.\nconst lastIds = new WeakMap<WebSocketClient<any, any>, number>();\n\ninterface Pending<In> {\n resolve(reply: In): void;\n reject(reason: unknown): void;\n /** The socket the request went out on, or `null` while it waits in the client's queue. */\n socket: WebSocket | null;\n}\n\n/**\n * Send requests and await their replies, matched by an id the library generates.\n *\n * Replies are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * type Request = { type: 'join'; room: string } | { type: 'leave' };\n *\n * export const rpc = createWebSocketRequests(game, {\n * send: (message: Request, id) => ({ ...message, id }),\n * reply: message => (message.type === 'reply' ? message.id : undefined),\n * error: message => (message.type === 'reply' && message.error ? new Error(message.error) : undefined)\n * });\n *\n * const reply = await rpc.request({ type: 'join', room: 'lobby' }, { timeout: 5000 });\n * ```\n */\n// `const` + `NoInfer`: `In` and `Out` come from the client only, with literals kept unwidened;\n// `Req` comes from how `send` annotates its parameter.\nexport function createWebSocketRequests<Req, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>\n): WebSocketRequests<Req, In> {\n const waiting = new Map<string, Pending<In>>();\n\n function rejectWhere(test: (entry: Pending<In>) => boolean, reason: () => unknown) {\n for (const entry of [...waiting.values()]) if (test(entry)) entry.reject(reason());\n }\n\n const offs = [\n client.on('message', message => {\n const id = options.reply(message);\n const entry = id == null ? undefined : waiting.get(String(id));\n if (!entry) return;\n const error = options.error?.(message);\n if (error === undefined) entry.resolve(message);\n else entry.reject(error);\n }),\n // `open` listeners run before the client flushes its queue: queued requests go out on this socket.\n client.on('open', () => {\n for (const entry of waiting.values()) entry.socket ??= client.socket;\n }),\n client.subscribe(() => {\n const { status } = client.getSnapshot();\n if (status === 'closed' || status === 'idle') {\n // The queue was cleared too, so nothing still waiting can be sent.\n rejectWhere(\n () => true,\n () => new Error('WebSocket was closed before the request was answered')\n );\n } else {\n rejectWhere(\n entry => entry.socket !== null && entry.socket !== client.socket,\n () => new Error('WebSocket connection was lost before the request was answered')\n );\n }\n })\n ];\n\n return {\n client,\n request(message, requestOptions = {}) {\n const { signal } = requestOptions;\n if (signal?.aborted) return Promise.reject(signal.reason);\n\n const id = (lastIds.get(client) ?? 0) + 1;\n lastIds.set(client, id);\n const key = String(id);\n const timeout = requestOptions.timeout ?? options.timeout ?? 10_000;\n\n return new Promise<In>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const release = client.acquire();\n const onAbort = () => entry.reject(signal!.reason);\n\n function settle() {\n waiting.delete(key);\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n release();\n }\n\n const entry: Pending<In> = {\n socket: null,\n resolve(reply) {\n settle();\n resolve(reply);\n },\n reject(reason) {\n settle();\n reject(reason);\n }\n };\n waiting.set(key, entry);\n signal?.addEventListener('abort', onAbort, { once: true });\n if (timeout > 0 && timeout < Infinity) {\n timer = setTimeout(\n () =>\n entry.reject(\n new DOMException(`Request ${id} timed out after ${timeout}ms`, 'TimeoutError')\n ),\n timeout\n );\n }\n\n const { status } = client.getSnapshot();\n if (status === 'closed' || status === 'idle') {\n // Closed until someone reconnects it, or (idle after acquiring) it can't connect here.\n entry.reject(new Error(`WebSocket is ${status}: request not sent`));\n return;\n }\n let sent: boolean;\n try {\n sent = client.send(options.send(message, id), {\n ...requestOptions,\n onDrop() {\n entry.reject(new Error('Request was dropped from the send queue before it was sent'));\n requestOptions.onDrop?.();\n }\n });\n } catch (error) {\n entry.reject(error);\n return;\n }\n if (sent) entry.socket = client.socket;\n // Open but not sent: `maxBuffered` dropped it, and nothing will send it later.\n else if (client.socket?.readyState === 1)\n entry.reject(new Error('WebSocket send buffer is full: request dropped'));\n else if (requestOptions.volatile)\n entry.reject(new Error('WebSocket is not open: request dropped'));\n });\n },\n pending: () => waiting.size,\n dispose() {\n offs.forEach(off => off());\n rejectWhere(\n () => true,\n () => new Error('Requests were disposed')\n );\n }\n };\n}\n","import type { WebSocketClient } from './types';\n\n/** What `request` returns for a request: any object with these fields, such as the message itself. */\ntype RequestFields = { id: number | string; method: string; params?: unknown; timeout?: number };\n\n/**\n * The type of `params` in `Q`, keeping `undefined` when they're optional and giving `undefined`\n * when there are none. (Inferring `params?: P` directly would drop the `undefined`.)\n */\ntype ParamsOf<Q> = Q extends unknown\n ? 'params' extends keyof Q\n ? Q['params' & keyof Q]\n : undefined\n : never;\n\n/**\n * Options for {@link createWebSocketResponder}: how the server's requests and your replies look\n * on the wire.\n *\n * @typeParam Q - What `request` returns. Handlers receive its `params`.\n * @typeParam R - What handlers return, from the annotation on `respond`'s `result`.\n */\nexport interface WebSocketResponderOptions<Q extends RequestFields, R, In, Out> {\n /**\n * Recognize a request from the server: its `id`, the `method` handlers are registered for,\n * and the `params` they receive. Return `undefined` (or `null`) for any other message.\n * A `timeout` (in ms) overrides the manager's for this request.\n *\n * `params` come from the server, so validate them before acting on them.\n */\n request: (message: In) => Q | null | undefined;\n /** Build the reply to request `id`. Annotate `result` to type what handlers return. */\n respond: (id: number | string, result: R) => Out;\n /**\n * Build the error reply to request `id`: what a handler threw, a `NotFoundError` `DOMException`\n * when nothing is registered for the method, a `TimeoutError` after `timeout`, or an\n * `AbortError` from `dispose()`.\n */\n error: (id: number | string, error: unknown) => Out;\n /**\n * The id of a request the server withdrew, or `undefined` (or `null`) if the message isn't a\n * cancellation. The request's `signal` aborts and nothing is sent.\n */\n cancel?: (message: In) => number | string | null | undefined;\n /**\n * Time to answer a request, in ms. When it runs out, the `error` reply (a `TimeoutError`)\n * is sent and the request's `signal` aborts.\n * @default Infinity\n */\n timeout?: number;\n}\n\n/** A request from the server that hasn't been answered yet. */\nexport interface IncomingRequest<P = unknown, R = unknown> {\n /** The id the server sent. Replies carry it back. */\n readonly id: number | string;\n /** The method it was sent for. */\n readonly method: string;\n /** The `params` from `request`. They come from the server, so validate them. */\n readonly params: P;\n /**\n * Aborts when the answer is no longer wanted: the server cancelled the request, it timed out,\n * the connection it arrived on closed, the responder was disposed, or it was answered with\n * `respond` or `reject` while its handler was still running.\n */\n readonly signal: AbortSignal;\n /**\n * Reply with `result`. Only the first answer counts.\n * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.\n */\n respond(result: R): boolean;\n /**\n * Reply with an error, built by the `error` option. Only the first answer counts.\n * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.\n */\n reject(error: unknown): boolean;\n}\n\n/**\n * Answers a request in code. Return (or resolve) the result to reply with it; throw (or reject)\n * to send the `error` reply instead.\n */\nexport type RequestHandler<P = unknown, R = unknown> = (\n params: P,\n request: IncomingRequest<P, R>\n) => R | PromiseLike<R>;\n\n/** Answers the server's requests on one client. Create with {@link createWebSocketResponder}. */\nexport interface WebSocketResponder<P = unknown, R = unknown> {\n /** The client requests arrive on. Hooks reading the responder keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Answer requests for `method` until the returned function is called.\n *\n * With a `handler`, requests are answered in code. Without one, they wait in\n * {@link getSnapshot} until something calls `respond` or `reject` on them, e.g. a dialog\n * that asks the user. When several registrations exist for one method, the newest one takes\n * new requests, and unregistering it hands them back to the previous one. Requests for a\n * method with no registration get a `NotFoundError` reply.\n *\n * @returns An unregister function (safe to call more than once). Requests already waiting stay.\n */\n onRequest(method: string, handler?: RequestHandler<P, R>): () => void;\n /**\n * Requests waiting for an answer from outside a handler, oldest first. Returns the same array\n * until it changes.\n */\n getSnapshot(): readonly IncomingRequest<P, R>[];\n /** Called whenever {@link getSnapshot} changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /**\n * Stop answering: send an `AbortError` reply to every request in flight and stop listening.\n * Only needed for responders created dynamically.\n */\n dispose(): void;\n}\n\ninterface Entry {\n /** The socket the request arrived on. Its reply can only go back on that one. */\n readonly socket: WebSocket | null;\n /** Forget the request and abort its signal, without replying. */\n drop(reason: DOMException): void;\n /** Forget the request, abort its signal and send the `error` reply, both with `error`. */\n fail(error: DOMException): void;\n}\n\nconst VOLATILE = { volatile: true };\nconst abortError = (message: string) => new DOMException(message, 'AbortError');\n\n/**\n * Answer requests the server sends: run a handler for tools that only exist in the browser\n * (selection, clipboard, geolocation), or let a person answer, e.g. to approve an agent's action.\n * The reverse of `createWebSocketRequests`.\n *\n * Every request gets exactly one reply while its connection lives: the handler's result, an\n * `error` reply when it throws, has no registration or times out. When the connection a request\n * arrived on closes, the request is dropped and nothing is sent, since the server can't match a\n * reply on a new connection. Replies are never queued.\n *\n * Requests are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * export const tools = createWebSocketResponder(agent, {\n * request: message => (message.type === 'call' ? message : undefined),\n * respond: (id, result: unknown) => ({ type: 'result', id, result }),\n * error: (id, error) => ({ type: 'result', id, error: String(error) })\n * });\n *\n * tools.onRequest('get_selection', () => window.getSelection()?.toString() ?? '');\n *\n * // In a component: requests a person answers.\n * const approvals = useAgentApproval(tools, 'approve');\n * approvals[0]?.respond({ approved: true });\n * ```\n */\n// `const` + `NoInfer`: `In` and `Out` come from the client only, with literals kept unwidened;\n// `Q` comes from what `request` returns and `R` from how `respond` annotates `result`.\nexport function createWebSocketResponder<Q extends RequestFields, R, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketResponderOptions<Q, R, NoInfer<In>, NoInfer<Out>>\n): WebSocketResponder<ParamsOf<Q>, R> {\n type P = ParamsOf<Q>;\n const entries = new Map<string, Entry>();\n const registrations = new Map<string, { handler?: RequestHandler<P, R> }[]>();\n const listeners = new Set<() => void>();\n let waiting: readonly IncomingRequest<P, R>[] = [];\n\n function setWaiting(next: readonly IncomingRequest<P, R>[]) {\n waiting = next;\n for (const listener of [...listeners]) listener();\n }\n\n /** Send a reply, or an `error` reply if building or encoding it throws. */\n function reply(id: number | string, build: () => Out): boolean {\n try {\n return client.send(build(), VOLATILE);\n } catch (error) {\n return client.send(options.error(id, error), VOLATILE);\n }\n }\n\n function receive(incoming: Q) {\n const { id, method } = incoming;\n const key = String(id);\n if (entries.has(key)) return; // sent again while it is being answered\n const registration = registrations.get(method)?.at(-1);\n if (!registration) {\n const error = new DOMException(`No handler for request method \"${method}\"`, 'NotFoundError');\n reply(id, () => options.error(id, error));\n return;\n }\n\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let done = false;\n let running = false;\n\n function settle(build: (() => Out) | null, reason?: unknown) {\n if (done) return false;\n done = true;\n entries.delete(key);\n clearTimeout(timer);\n if (waiting.includes(request)) setWaiting(waiting.filter(entry => entry !== request));\n if (reason !== undefined) controller.abort(reason);\n return build ? reply(id, build) : false;\n }\n\n // An answer from outside the handler makes the handler's work moot.\n const answeredElsewhere = () =>\n running ? abortError(`Request ${id} was answered elsewhere`) : undefined;\n const request: IncomingRequest<P, R> = {\n id,\n method,\n params: incoming.params as P,\n signal: controller.signal,\n respond: result => settle(() => options.respond(id, result), answeredElsewhere()),\n reject: error => settle(() => options.error(id, error), answeredElsewhere())\n };\n const fail = (error: DOMException) => {\n settle(() => options.error(id, error), error);\n };\n // Registered before the handler runs, so a handler that closes the socket drops its own request.\n entries.set(key, {\n socket: client.socket,\n drop: reason => {\n settle(null, reason);\n },\n fail\n });\n\n const timeout = incoming.timeout ?? options.timeout ?? Infinity;\n if (timeout > 0 && timeout < Infinity) {\n timer = setTimeout(\n () =>\n fail(\n new DOMException(`Request ${id} was not answered within ${timeout}ms`, 'TimeoutError')\n ),\n timeout\n );\n }\n\n const { handler } = registration;\n if (!handler) {\n setWaiting([...waiting, request]);\n return;\n }\n running = true;\n // Also catches a handler that throws synchronously.\n new Promise<R>(resolve => resolve(handler(request.params, request))).then(\n result => {\n running = false;\n request.respond(result);\n },\n error => {\n running = false;\n request.reject(error);\n }\n );\n }\n\n const offs = [\n client.on('message', message => {\n const incoming = options.request(message);\n if (incoming != null) {\n receive(incoming);\n return;\n }\n const id = options.cancel?.(message);\n if (id != null) {\n entries.get(String(id))?.drop(abortError(`Request ${id} was cancelled`));\n }\n }),\n // Every close, reconnect and teardown replaces `client.socket` and notifies.\n client.subscribe(() => {\n for (const entry of [...entries.values()]) {\n if (entry.socket !== client.socket) {\n entry.drop(abortError('WebSocket connection was lost before the request was answered'));\n }\n }\n })\n ];\n\n return {\n client,\n onRequest(method, handler) {\n let stack = registrations.get(method);\n if (!stack) registrations.set(method, (stack = []));\n const registration = { handler };\n stack.push(registration);\n return () => {\n const index = stack.indexOf(registration);\n if (index !== -1) stack.splice(index, 1);\n };\n },\n getSnapshot: () => waiting,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n offs.forEach(off => off());\n registrations.clear();\n for (const entry of [...entries.values()]) entry.fail(abortError('Responder was disposed'));\n }\n };\n}\n","import type { WebSocketLatency } from './latency';\nimport type { WebSocketClient } from './types';\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/** Options for {@link createWebSocketSendRate}. */\nexport interface WebSocketSendRateOptions {\n /**\n * Ticks per second while the connection keeps up.\n * @default 30\n */\n maxRate?: number;\n /**\n * The rate never drops below this, in ticks per second.\n * @default 5\n */\n minRate?: number;\n /**\n * Bytes waiting in the browser's send buffer (`socket.bufferedAmount`) above which a tick\n * sends nothing and the rate halves.\n * @default 1024\n */\n maxBuffered?: number;\n /**\n * Measurements from `createWebSocketLatency` on the same client. With them, a round-trip time\n * that rises also lowers the rate. Without them, only the send buffer is watched.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot'>;\n /**\n * How far `rtt` may rise above the lowest one measured on this connection before the rate\n * halves, in ms. A steady high ping keeps the full rate; only a rising one counts.\n * @default 100\n */\n maxRttIncrease?: number;\n}\n\n/** The current send rate. A new object is created on every change. */\nexport interface SendRate {\n /** Ticks per second, rounded. */\n readonly rate: number;\n /**\n * Whether the last tick found the link congested: the send buffer above `maxBuffered`, or\n * `rtt` risen more than `maxRttIncrease`.\n */\n readonly congested: boolean;\n}\n\n/** Keyed sends coalesced at a rate that adapts to the link. Create with {@link createWebSocketSendRate}. */\nexport interface WebSocketSendRate<Out> {\n /** The client the messages are sent on. */\n readonly client: WebSocketClient<any, Out>;\n /**\n * Send `message` at the next tick. A message with the same `key` still waiting for it is\n * replaced, so only the newest one goes out. Sent with `volatile`.\n */\n send(message: Out, key: string): void;\n /** Send everything waiting now, e.g. right before a one-shot action that must carry the latest aim. */\n flush(): void;\n /** The current {@link SendRate}. Returns the same object until it changes. */\n getSnapshot(): SendRate;\n /** Called whenever the rate or `congested` changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening. Only needed for instances created dynamically. */\n dispose(): void;\n}\n\nconst VOLATILE = { volatile: true };\n\n/**\n * Send high-rate state, such as aim, cursor or position, at a rate that adapts to the\n * connection. Messages are coalesced per key between ticks. The rate drops by half when the\n * send buffer fills up or the round trip grows, and climbs back one tick per second at a time\n * when the link keeps up, so players on a poor connection degrade smoothly instead of building\n * up lag.\n *\n * Ticks run only while the socket is open and something is waiting. Messages waiting during a\n * reconnect go out after it; `close()` drops them. It doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * export const stream = createWebSocketSendRate(game, { latency, maxRate: 30 });\n *\n * // On every pointer move: at most 30 a second, fewer on a congested link.\n * stream.send({ type: 'aim', angle }, 'aim');\n * ```\n */\nexport function createWebSocketSendRate<Out>(\n client: WebSocketClient<any, Out>,\n options: WebSocketSendRateOptions = {}\n): WebSocketSendRate<Out> {\n const { maxBuffered = 1024, latency, maxRttIncrease = 100 } = options;\n const maxRate = options.maxRate ?? 30;\n const minRate = Math.min(options.minRate ?? 5, maxRate);\n const listeners = new Set<() => void>();\n // Insertion order is send order: a replaced message moves to the end.\n const pending = new Map<string, Out>();\n let rate = maxRate;\n let snapshot: SendRate = { rate: maxRate, congested: false };\n let last = -Infinity; // `performance.now()` at the last tick\n let best = Infinity; // the lowest `rtt` on this connection\n let slow = false; // `rtt` has risen too far above `best`\n let measured: unknown; // the latency snapshot already reacted to\n let timer: Timer | undefined;\n let disposed = false;\n\n function flush() {\n for (const [key, message] of pending) {\n if (!client.send(message, VOLATILE)) return; // not open: keep the rest for later\n pending.delete(key);\n }\n }\n\n function publish(congested: boolean) {\n const rounded = Math.round(rate);\n if (rounded === snapshot.rate && congested === snapshot.congested) return;\n snapshot = { rate: rounded, congested };\n for (const listener of [...listeners]) listener();\n }\n\n function schedule() {\n if (disposed || timer !== undefined || !pending.size || client.getSnapshot().status !== 'open')\n return;\n // Right away after a pause, otherwise one interval after the last tick.\n timer = setTimeout(tick, Math.max(0, last + 1000 / rate - performance.now()));\n }\n\n function stop() {\n clearTimeout(timer);\n timer = undefined;\n }\n\n // Additive increase, multiplicative decrease, as TCP does.\n function tick() {\n timer = undefined;\n last = performance.now();\n const measurement = latency?.getSnapshot();\n if (measurement !== measured) {\n // React to each measurement once.\n measured = measurement;\n const rtt = measurement?.rtt;\n if (rtt !== undefined) {\n best = Math.min(best, rtt);\n slow = rtt - best > maxRttIncrease;\n if (slow) rate /= 2;\n }\n }\n // Checked once per tick, not per message, so messages in one tick don't count against each other.\n const full = (client.socket?.bufferedAmount ?? 0) > maxBuffered;\n if (full) rate /= 2;\n else {\n flush();\n if (!slow) rate++;\n }\n rate = Math.min(maxRate, Math.max(minRate, rate));\n publish(full || slow);\n schedule();\n }\n\n const offs = [\n client.on('open', () => {\n // A new connection may take a different route: measure its best round trip afresh, and\n // ignore the last connection's measurement, which stays readable until a new one arrives.\n best = Infinity;\n slow = false;\n measured = latency?.getSnapshot();\n schedule(); // after the client's own queue, which is sent once `open` listeners return\n }),\n client.subscribe(() => {\n const { status } = client.getSnapshot();\n if (status !== 'open') stop();\n // Like the client's queue: kept through a reconnect, dropped by `close()` or giving up.\n if (status === 'closed' || status === 'idle') pending.clear();\n })\n ];\n\n return {\n client,\n send(message, key) {\n pending.delete(key);\n pending.set(key, message);\n schedule();\n },\n flush,\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n stop();\n pending.clear();\n offs.forEach(off => off());\n }\n };\n}\n","import type { WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketState}. */\nexport interface WebSocketStateOptions<S, In> {\n /** The state before any message arrives, and what `reset()` returns to. */\n initialState: S;\n /**\n * Fold one incoming message into the state. Must be pure: return a new object for a\n * change, or the same `state` to ignore the message (subscribers aren't notified).\n */\n reduce: (state: S, message: In) => S;\n /**\n * `'frame'`: notify subscribers at most once per animation frame instead of once per\n * message, so a fast stream (tokens, tickers, game state) renders once per frame.\n * `getState()` is always current; only notifications wait. `setState` and `reset` still\n * notify right away.\n *\n * Browsers pause animation frames in background tabs: the state keeps up, and subscribers\n * hear about it when the tab is visible again. Without `requestAnimationFrame` (Node, some\n * workers), it waits about 16 ms instead.\n */\n batch?: 'frame';\n}\n\n/**\n * State derived from a client's messages. Read it with `useWebSocketState(store, selector)`,\n * or with `getState`/`subscribe` outside React.\n *\n * @typeParam S - The state type. Don't use a function type: `setState` treats functions as updaters.\n */\nexport interface WebSocketState<S> {\n /** The client whose messages this store reduces. Hooks reading the store keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /** The `initialState` it was created with. Used for server rendering and hydration. */\n readonly initialState: S;\n /** The current state. Returns the same object until it changes. */\n getState(): S;\n /** Called whenever the state changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Replace the state, or update it from the current one, e.g. for optimistic updates. */\n setState(update: S | ((state: S) => S)): void;\n /** Go back to `initialState`. */\n reset(): void;\n /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */\n dispose(): void;\n}\n\n/**\n * Keep state derived from a client's messages, like a reducer that runs on every message.\n * It starts listening immediately and keeps the state across reconnects; it doesn't open\n * the connection by itself.\n *\n * @example\n * ```ts\n * const prices = createWebSocket<Tick>('wss://api.example.com/prices', { json: true });\n *\n * export const priceState = createWebSocketState(prices, {\n * initialState: {} as Record<string, number>,\n * reduce: (state, tick) => ({ ...state, [tick.symbol]: tick.price })\n * });\n *\n * // In a component: re-renders only when ACME's price changes.\n * const acme = useWebSocketState(priceState, state => state.ACME);\n * ```\n */\nexport function createWebSocketState<S, In>(\n client: WebSocketClient<In, any>,\n // `In` comes from the client only, not from how `reduce` annotates its parameter.\n options: WebSocketStateOptions<S, NoInfer<In>>\n): WebSocketState<S> {\n const { initialState, reduce, batch } = options;\n let state = initialState;\n // What subscribers were last told about, so a frame that finds nothing new stays quiet.\n let notified = state;\n let frame = false;\n const listeners = new Set<() => void>();\n\n function notify() {\n if (Object.is(state, notified)) return;\n notified = state;\n for (const listener of [...listeners]) listener();\n }\n\n function flush() {\n frame = false;\n notify();\n }\n\n function update(change: S | ((state: S) => S), later?: boolean) {\n const next = typeof change === 'function' ? (change as (state: S) => S)(state) : change;\n if (Object.is(next, state)) return;\n state = next;\n if (!later) notify();\n else if (!frame) {\n frame = true;\n // Node and some workers have no animation frames: wait about one instead.\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(flush);\n else setTimeout(flush, 16);\n }\n }\n\n // A throwing reducer leaves the state unchanged; the client re-throws the error asynchronously.\n const off = client.on('message', message =>\n update(current => reduce(current, message), batch === 'frame')\n );\n\n return {\n client,\n initialState,\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setState: change => update(change),\n reset: () => update(initialState),\n dispose: off\n };\n}\n","import type { WebSocketClient } from './types';\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/** Options for {@link createWebSocketTopics}: the messages your server expects. */\nexport interface WebSocketTopicsOptions<Out> {\n /** The message that subscribes to `topic`. */\n subscribe: (topic: string) => Out;\n /** The message that unsubscribes from `topic`. Omit it if your server has none. */\n unsubscribe?: (topic: string) => Out;\n}\n\n/** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */\nexport interface WebSocketTopics {\n /** The client the subscription messages are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Hold a subscription to `topic`, and the client's connection, until the returned\n * function is called. The release function is safe to call more than once.\n */\n acquire(topic: string): () => void;\n /** The topics currently held, in the order they were first acquired. */\n active(): string[];\n /** Stop managing subscriptions. Only needed for managers created dynamically. */\n dispose(): void;\n}\n\n/**\n * Manage topic subscriptions that survive reconnects.\n *\n * - The first holder of a topic sends `subscribe(topic)`. Later holders share it.\n * - A tick after the last holder releases it, `unsubscribe(topic)` is sent, so StrictMode\n * and route transitions don't churn subscriptions.\n * - After every reconnect, every held topic is subscribed again on the new socket, before\n * messages queued while disconnected are sent.\n *\n * Subscriptions are only sent while the socket is open; nothing is queued for them.\n *\n * @example\n * ```ts\n * export const topics = createWebSocketTopics(live, {\n * subscribe: topic => ({ type: 'subscribe', topic }),\n * unsubscribe: topic => ({ type: 'unsubscribe', topic })\n * });\n *\n * // In a component:\n * useWebSocketTopic(topics, `prices:${symbol}`);\n * ```\n */\n// `const` + `NoInfer`: take `Out` from the client only, and keep literals such as\n// `type: 'subscribe'` from widening to `string` inside the callbacks.\nexport function createWebSocketTopics<const Out>(\n client: WebSocketClient<any, Out>,\n options: WebSocketTopicsOptions<NoInfer<Out>>\n): WebSocketTopics {\n const counts = new Map<string, number>();\n const pendingRemoval = new Map<string, Timer>();\n // Topics subscribed on `sentOn`. A new socket starts with none, whatever the old one had.\n let sentOn: WebSocket | null = null;\n let sent = new Set<string>();\n\n function isOpen() {\n return client.getSnapshot().status === 'open' && client.socket !== null;\n }\n\n function subscribe(topic: string) {\n if (!isOpen()) return; // sent on `open` instead\n if (client.socket !== sentOn) {\n sentOn = client.socket;\n sent = new Set();\n }\n if (sent.has(topic)) return;\n sent.add(topic);\n client.send(options.subscribe(topic));\n }\n\n function unsubscribe(topic: string) {\n if (!isOpen() || client.socket !== sentOn || !sent.delete(topic)) return;\n if (options.unsubscribe) client.send(options.unsubscribe(topic));\n }\n\n // `open` listeners run before the client flushes its queue.\n const off = client.on('open', () => {\n sentOn = client.socket;\n sent = new Set();\n for (const topic of counts.keys()) subscribe(topic);\n });\n\n return {\n client,\n acquire(topic) {\n const releaseConnection = client.acquire();\n clearTimeout(pendingRemoval.get(topic));\n pendingRemoval.delete(topic);\n counts.set(topic, (counts.get(topic) ?? 0) + 1);\n subscribe(topic);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const remaining = (counts.get(topic) ?? 1) - 1;\n if (remaining > 0) {\n counts.set(topic, remaining);\n } else {\n counts.delete(topic);\n pendingRemoval.set(\n topic,\n setTimeout(() => {\n pendingRemoval.delete(topic);\n if (!counts.has(topic)) unsubscribe(topic);\n }, 0)\n );\n }\n releaseConnection();\n };\n },\n active: () => [...counts.keys()],\n dispose() {\n off();\n for (const timer of pendingRemoval.values()) clearTimeout(timer);\n pendingRemoval.clear();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;AA8QA,IAAa,eAAb,cAAkC,MAAM;;CAEtC;;CAEA;CAEA,YACE,SACA,MACA,SACA;EACA,MAAM,SAAS,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EAClF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;CACzB;AACF;;;AChRA,MAAM,OAAO;AAEb,MAAM,qBAAqB;CACzB,aAAa;CACb,UAAU;CACV,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;AAMA,MAAM,cAAc;AAiBpB,SAAS,iBAA2B;CAClC,IAAI;CACJ,IAAI;CACJ,MAAM,UAAU,IAAI,SAAe,KAAK,QAAQ;EAC9C,UAAU;EACV,SAAS;CACX,CAAC;CACD,QAAQ,SAAS;CAEjB,QAAQ,YAAY,CAAC,CAAC;CACtB,MAAM,WAAqB;EACzB;EACA,SAAS;EACT,UAAU;GACR,IAAI,SAAS,SAAS;GACtB,SAAS,U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O,GAAG,cAAc;EAClC,SAAS,OAAO;EAChB,uBAAO,IAAI,IAAI;EACf,KAAK,MAAM,SAAS,OAAO,KAAK,GAAG,UAAU,KAAK;CACpD,CAAC;CAED,OAAO;EACL;EACA,QAAQ,OAAO;GACb,MAAM,oBAAoB,OAAO,QAAQ;GACzC,aAAa,eAAe,IAAI,KAAK,CAAC;GACtC,eAAe,OAAO,KAAK;GAC3B,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;GAC9C,UAAU,KAAK;GAEf,IAAI,WAAW;GACf,aAAa;IACX,IAAI,UAAU;IACd,WAAW;IACX,MAAM,aAAa,OAAO,IAAI,KAAK,KAAK,KAAK;IAC7C,IAAI,YAAY,GACd,OAAO,IAAI,OAAO,SAAS;SACtB;KACL,OAAO,OAAO,KAAK;KACnB,eAAe,IACb,OACA,iBAAiB;MACf,eAAe,OAAO,KAAK;MAC3B,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG,YAAY,KAAK;KAC3C,GAAG,CAAC,CACN;IACF;IACA,kBAAkB;GACpB;EACF;EACA,cAAc,CAAC,GAAG,OAAO,KAAK,CAAC;EAC/B,UAAU;GACR,IAAI;GACJ,KAAK,MAAM,SAAS,eAAe,OAAO,GAAG,aAAa,KAAK;GAC/D,eAAe,MAAM;EACvB;CACF;AACF"}
1
+ {"version":3,"file":"core.js","names":["VOLATILE","VOLATILE"],"sources":["../src/types.ts","../src/client.ts","../src/latency.ts","../src/requests.ts","../src/responder.ts","../src/sendrate.ts","../src/state.ts","../src/topics.ts"],"sourcesContent":["/**\n * Where to connect: a URL, or a function that returns one (sync or async).\n *\n * A function is called before **every** connection attempt, including reconnects,\n * so it can put a fresh auth token in the URL. If it throws or rejects, that counts\n * as a failed attempt and is retried with backoff.\n *\n * @example\n * ```ts\n * createWebSocket(async () => `wss://api.example.com/live?token=${await getToken()}`);\n * ```\n */\nexport type UrlSource = string | (() => string | Promise<string>);\n\n/**\n * Connection state.\n *\n * - `idle`: not connected and not trying to be. Nobody is using the client yet, or everyone stopped.\n * - `connecting`: the first attempt is in progress.\n * - `open`: connected. `send()` goes out immediately.\n * - `reconnecting`: the connection dropped (or an attempt failed) and a retry is scheduled or in progress.\n * - `closed`: stopped for good, by `close()` or after giving up on reconnecting.\n * It stays closed until `connect()` or `reconnect()` is called, or every hook unmounts.\n */\nexport type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';\n\n/** The client's state as seen by React. A new object is created on every change. */\nexport interface Snapshot<In> {\n /** Connection state. */\n readonly status: Status;\n /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */\n readonly lastMessage: In | undefined;\n /** Consecutive failed attempts since the last successful open. `0` while open. */\n readonly attempt: number;\n}\n\n/** Details of a closed connection, from the browser's `CloseEvent`. */\nexport interface CloseInfo {\n /** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */\n readonly code: number;\n /** Close reason sent by the side that closed the connection. Often empty. */\n readonly reason: string;\n /** Whether the closing handshake completed. */\n readonly wasClean: boolean;\n}\n\n/** Anything `WebSocket.prototype.send` accepts: a string, `Blob`, `ArrayBuffer` or typed array. */\nexport type SendData = Parameters<WebSocket['send']>[0];\n\n/** Reconnect timing. Delay before attempt `n` = `min(maxDelay, minDelay * factor ** (n - 1))`, minus jitter. */\nexport interface ReconnectOptions {\n /**\n * Maximum consecutive reconnect attempts. When the last one fails too, the client\n * gives up: the status becomes `closed` and `ready` rejects. `0` never retries.\n * @default Infinity\n */\n maxAttempts?: number;\n /**\n * Delay before the first retry, in ms.\n * @default 1000\n */\n minDelay?: number;\n /**\n * Upper bound for the delay, in ms.\n * @default 30000\n */\n maxDelay?: number;\n /**\n * Backoff multiplier applied per attempt.\n * @default 2\n */\n factor?: number;\n /**\n * Randomly shave up to this fraction (0–1) off each delay, so that many clients\n * dropped at once don't all reconnect at the same moment.\n * @default 0.5\n */\n jitter?: number;\n /**\n * Called on every unexpected close. Return `false` to stop reconnecting.\n *\n * @example\n * ```ts\n * // Don't retry when the server rejects our credentials.\n * shouldReconnect: close => close.code !== 4001\n * ```\n * @default () => true\n */\n shouldReconnect?: (close: CloseInfo) => boolean;\n}\n\n/** Application-level keep-alive. Useful behind proxies that drop idle connections. */\nexport interface HeartbeatOptions {\n /** Send `message` every `interval` ms while open. */\n interval: number;\n /**\n * Sent as-is (it is not passed through `serialize` or `json`).\n * @default 'ping'\n */\n message?: string;\n /** Incoming data equal to this string is swallowed instead of being delivered as a message. */\n pong?: string;\n /**\n * If nothing at all arrives within this many ms after a ping, the connection is\n * treated as dead: it closes with code `4000` and reconnects.\n */\n timeout?: number;\n}\n\n/** Per-message options for `send()`. */\nexport interface SendOptions {\n /**\n * Drop the message instead of queueing it when the socket isn't open. For data that\n * is stale by the time a reconnect finishes, such as player input or cursor positions.\n * @default false\n */\n volatile?: boolean;\n /**\n * Keep only the newest queued message with this key. Sending again with the same key\n * while disconnected replaces the earlier one, which moves to the back of the queue\n * (or of the `priority` messages, for a priority one).\n * For state where only the latest value matters, such as \"my position is now (x, y)\".\n */\n key?: string;\n /**\n * Queue this message ahead of every message queued without `priority`, after earlier\n * priority messages. For control messages that must not wait behind a backlog, such as\n * cancel, interrupt or a token refresh. Messages sent from `open` listeners still go first.\n *\n * It only matters while the socket isn't open: once a message is handed to the browser,\n * nothing can overtake it. To keep that buffer short, send bulky streams with `maxBuffered`.\n * @default false\n */\n priority?: boolean;\n /**\n * Drop the message instead of sending it while more than this many bytes are already\n * waiting in the browser's send buffer (`socket.bufferedAmount`). For high-rate streams on\n * a slow link, such as audio frames or per-tick input, where a late message is worse than\n * none. `send()` returns `false`, and `onDrop` isn't called.\n *\n * Only checked while the socket is open: a message queued while disconnected is sent on\n * open regardless. `bufferedAmount` includes what you sent earlier in the same task, so set\n * it well above one burst of messages.\n *\n * @example\n * ```ts\n * voice.send(frame, { volatile: true, maxBuffered: 64 * 1024 });\n * ```\n */\n maxBuffered?: number;\n /**\n * Called if the message is dropped from the queue without being sent: replaced by a\n * newer message with the same `key`, or evicted by `queue.limit`. Not called when the\n * queue is cleared because the client closed or gave up, or when `send()` drops the\n * message right away (`volatile` while not open, or `maxBuffered`) and returns `false`.\n */\n onDrop?: () => void;\n}\n\n/** Bounds for the send queue. */\nexport interface QueueOptions {\n /**\n * Maximum number of messages held while not connected. When full, the oldest\n * message is dropped, skipping `priority` messages unless nothing else is queued.\n * @default Infinity\n */\n limit?: number;\n}\n\n/**\n * The minimal [Standard Schema v1](https://standardschema.dev) interface, implemented\n * by zod (3.24+), valibot (1.0+), arktype (2.0+) and others. You don't need to\n * import this; pass your schema object directly.\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n };\n}\n\n/** The result of a Standard Schema `validate` call. */\nexport type StandardSchemaResult<Output> =\n | { readonly value: Output; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<{ readonly message: string }> };\n\n/**\n * Connection options, shared by `createWebSocket(url, options)` and `useWebSocket(url, options)`.\n *\n * @typeParam In - Type of incoming messages (after `parse`/`json`/`schema`).\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketOptions<In = unknown, Out = unknown> {\n /** Sub-protocol(s) passed to the `WebSocket` constructor. */\n protocols?: string | string[];\n /**\n * How binary messages are exposed.\n * @default 'blob'\n */\n binaryType?: BinaryType;\n /**\n * `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail\n * to parse are reported to `onError` as a {@link MessageError} and not delivered.\n * @default false\n */\n json?: boolean;\n /**\n * Custom decoder for incoming `event.data`. Takes precedence over `json`.\n * Throwing reports a {@link MessageError} and drops the message.\n */\n parse?: (data: unknown) => unknown;\n /** Custom encoder for outgoing messages. Takes precedence over `json`. */\n serialize?: (message: Out) => SendData;\n /**\n * Validate incoming messages (after parsing) with any Standard Schema library.\n * Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.\n * The message type `In` is inferred from it.\n *\n * @example\n * ```ts\n * createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });\n * ```\n */\n schema?: StandardSchemaV1<unknown, In>;\n /**\n * Reconnect with exponential backoff after an unexpected close. `false` disables it.\n * @default true\n */\n reconnect?: boolean | ReconnectOptions;\n /** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */\n heartbeat?: HeartbeatOptions;\n /**\n * Buffer `send()` calls made while not connected and send them, in order, on open\n * (right after `open` listeners run).\n * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.\n * The queue is cleared by `close()` or when the client gives up.\n * @default true\n */\n queue?: boolean | QueueOptions;\n /**\n * Receives debug messages about connection attempts, retries and dropped messages.\n * @example\n * ```ts\n * logger: console.debug\n * ```\n */\n logger?: (message: string, ...details: unknown[]) => void;\n /**\n * `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.\n * When omitted, the global `WebSocket` is used in browsers. During a server render\n * (no `window`), nothing connects unless an implementation is passed.\n */\n WebSocket?: typeof WebSocket;\n}\n\n/**\n * Reported via the `error` event (and `onError`) when an incoming message can't be\n * decoded by `parse`/`json` or fails `schema` validation. The message is not delivered.\n *\n * @example\n * ```ts\n * onError(error) {\n * if (error instanceof MessageError) report(error.data, error.issues);\n * }\n * ```\n */\nexport class MessageError extends Error {\n /** The raw `event.data` that failed. */\n readonly data: unknown;\n /** Schema validation issues, when the message failed `schema`. */\n readonly issues: ReadonlyArray<{ readonly message: string }> | undefined;\n\n constructor(\n message: string,\n data: unknown,\n options?: { cause?: unknown; issues?: ReadonlyArray<{ readonly message: string }> }\n ) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'MessageError';\n this.data = data;\n this.issues = options?.issues;\n }\n}\n\n/** Events emitted by a client. Subscribe with `client.on(type, listener)` or `useWebSocketEvent`. */\nexport interface EventMap<In> {\n /**\n * The socket opened (initially or after a reconnect). Listeners run before queued\n * messages are sent, so a handshake sent from here goes out first.\n */\n open: (event: Event) => void;\n /** A message arrived and passed `parse` and `schema`. */\n message: (message: In, event: MessageEvent) => void;\n /** A socket closed, whether it will be retried or not. */\n close: (close: CloseInfo) => void;\n /**\n * A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,\n * or the `Error` thrown by the `WebSocket` constructor or a `url` function.\n */\n error: (error: Event | MessageError | Error) => void;\n}\n\n/**\n * A WebSocket connection that reconnects, queues, decodes and can be shared.\n * Create one with `createWebSocket()`.\n *\n * The connection is reference-counted: it opens when the first hook mounts (or\n * `ready` is read) and closes one tick after the last hook unmounts. Calling\n * `connect()` keeps it open regardless, until `close()`.\n *\n * @typeParam In - Type of incoming messages.\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketClient<In = unknown, Out = unknown> {\n /** The URL (or URL function) the client was created with. */\n readonly url: UrlSource;\n /**\n * A promise that resolves once the socket has opened. Reading it starts an idle client.\n *\n * It stays resolved through automatic reconnects, so `use(client.ready)` shows a\n * Suspense fallback only for the first connection, never on a network blip; use\n * `status` to show reconnects. It rejects when the client gives up reconnecting, when\n * `close()` is called, and during a server render. After that, `connect()` or\n * `reconnect()` make it a new pending promise.\n *\n * It is safe to pass to React 19's `use()`: the same promise is returned until its state\n * changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is\n * already settled.\n */\n readonly ready: Promise<void>;\n /** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */\n readonly socket: WebSocket | null;\n /** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** The current {@link Snapshot}. Returns the same object until something changes. */\n getSnapshot(): Snapshot<In>;\n /**\n * Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown\n * asynchronously, so one failing listener doesn't break the others.\n */\n on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;\n /**\n * Send a message (encoded with `serialize`/`json` if configured). If the socket isn't\n * open, the message is queued and sent on open (see the `queue` option), unless\n * `options.volatile` is set.\n * @returns `true` if it was sent immediately, `false` if it was queued or dropped\n * (`volatile` while not open, or `maxBuffered` while open).\n *\n * @example\n * ```ts\n * game.send({ type: 'input', dx, dy }, { volatile: true }); // never replayed after a reconnect\n * game.send({ type: 'position', x, y }, { key: 'position' }); // only the newest is queued\n * game.send({ type: 'leave' }, { priority: true }); // ahead of everything already queued\n * ```\n */\n send(message: Out, options?: SendOptions): boolean;\n /**\n * Start connecting, and keep the connection open even when no hook is using the\n * client, until `close()` is called. Does nothing if already connecting or open.\n */\n connect(): void;\n /**\n * Close the connection and stop reconnecting. The status becomes `closed` and the\n * send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`\n * to start again.\n * @param code - Close code. @default 1000\n */\n close(code?: number, reason?: string): void;\n /**\n * Drop the current socket (if any) and connect again immediately, resetting the\n * backoff. Also restarts a `closed` client.\n */\n reconnect(): void;\n /**\n * Hold the connection open until the returned function is called. This is what the\n * hooks use; call it yourself to integrate with non-React code.\n * @returns A release function (safe to call more than once).\n */\n acquire(): () => void;\n}\n","import {\n MessageError,\n type CloseInfo,\n type EventMap,\n type ReconnectOptions,\n type SendData,\n type SendOptions,\n type Snapshot,\n type StandardSchemaResult,\n type UrlSource,\n type WebSocketClient,\n type WebSocketOptions\n} from './types';\n\nconst OPEN = 1;\n\nconst RECONNECT_DEFAULTS = {\n maxAttempts: Infinity,\n minDelay: 1000,\n maxDelay: 30_000,\n factor: 2,\n jitter: 0.5\n} satisfies ReconnectOptions;\n\ntype Timer = ReturnType<typeof setTimeout> | undefined;\n\n// How long a connection opened only by reading `ready` waits for a holder before closing.\n// Long enough for React to retry a suspended render and commit its hooks.\nconst READY_GRACE = 5000;\n\n// React's `use()` reads `status`/`value`/`reason` off a thenable to skip suspending\n// when it is already settled.\ntype TrackedPromise = Promise<void> & {\n status: 'pending' | 'fulfilled' | 'rejected';\n value?: void;\n reason?: unknown;\n};\n\ninterface Deferred {\n readonly promise: TrackedPromise;\n settled: boolean;\n resolve(): void;\n reject(reason: unknown): void;\n}\n\nfunction createDeferred(): Deferred {\n let resolve!: () => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<void>((res, rej) => {\n resolve = res;\n reject = rej;\n }) as TrackedPromise;\n promise.status = 'pending';\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n promise.catch(() => {});\n const deferred: Deferred = {\n promise,\n settled: false,\n resolve() {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'fulfilled';\n promise.value = undefined;\n resolve();\n },\n reject(reason) {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'rejected';\n promise.reason = reason;\n reject(reason);\n }\n };\n return deferred;\n}\n\nfunction rethrowAsync(error: unknown) {\n queueMicrotask(() => {\n throw error;\n });\n}\n\nfunction isThenable<T>(value: unknown): value is PromiseLike<T> {\n return typeof (value as PromiseLike<T> | null)?.then === 'function';\n}\n\n/**\n * @internal Option key for a callback run when the client tears down, which lets the hooks'\n * URL registry forget clients nobody holds anymore. A registered symbol rather than an export,\n * because the hooks entry imports the client from the `core` entry at runtime.\n */\nconst ON_TEARDOWN = Symbol.for('react-websocket.onTeardown');\n\nfunction createClient<In = unknown, Out = unknown>(\n url: UrlSource,\n options: WebSocketOptions<In, Out> & { [ON_TEARDOWN]?: () => void } = {}\n): WebSocketClient<In, Out> {\n const onTeardown = options[ON_TEARDOWN];\n const log = options.logger ?? (() => {});\n const retry =\n options.reconnect === false\n ? null\n : {\n ...RECONNECT_DEFAULTS,\n ...(typeof options.reconnect === 'object' ? options.reconnect : {})\n };\n const queueLimit =\n options.queue === false\n ? 0\n : typeof options.queue === 'object'\n ? Math.max(0, options.queue.limit ?? Infinity)\n : Infinity;\n\n let snapshot: Snapshot<In> = { status: 'idle', lastMessage: undefined, attempt: 0 };\n const storeListeners = new Set<() => void>();\n const listeners: { [K in keyof EventMap<In>]: Set<EventMap<In>[K]> } = {\n open: new Set(),\n message: new Set(),\n close: new Set(),\n error: new Set()\n };\n\n let ws: WebSocket | null = null;\n let wanted = false;\n let refs = 0;\n // Set by a public `connect()`: stay connected after the last hook releases, until `close()`.\n let pinned = false;\n // Priority messages form the head of the queue, in the order they were sent.\n let pending: {\n data: SendData;\n key: string | undefined;\n priority: boolean | undefined;\n onDrop: (() => void) | undefined;\n }[] = [];\n let ready: Deferred | null = null;\n // Opened at least once since the client was last started. `ready` stays resolved through\n // automatic reconnects so `use(client.ready)` doesn't swap content for a fallback on every blip.\n let opened = false;\n let unavailable: Deferred | null = null;\n let startScheduled = false;\n let inbox: Promise<void> | null = null;\n // Bumped per connection attempt so a slow `url()` can't resurrect a cancelled one.\n let generation = 0;\n let windowBound = false;\n let retryTimer: Timer;\n let teardownTimer: Timer;\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n let pongTimer: Timer;\n\n function set(patch: Partial<Snapshot<In>>) {\n snapshot = { ...snapshot, ...patch };\n for (const listener of [...storeListeners]) {\n try {\n listener();\n } catch (error) {\n rethrowAsync(error);\n }\n }\n }\n\n function emit<K extends keyof EventMap<In>>(type: K, ...args: Parameters<EventMap<In>[K]>) {\n for (const listener of [...listeners[type]]) {\n try {\n (listener as (...a: Parameters<EventMap<In>[K]>) => void)(...args);\n } catch (error) {\n rethrowAsync(error);\n }\n }\n }\n\n function getImpl(): typeof WebSocket | undefined {\n if (options.WebSocket) return options.WebSocket;\n // Node has a global WebSocket too; don't connect from a server render.\n return typeof window === 'undefined' ? undefined : globalThis.WebSocket;\n }\n\n function rejectReady(reason: unknown) {\n if (!ready || ready.settled) ready = createDeferred();\n ready.reject(reason);\n }\n\n function retryNow() {\n if (retryTimer !== undefined) {\n log('network or visibility change, retrying now');\n open();\n }\n }\n\n function onVisibilityChange() {\n if (document.visibilityState === 'visible') retryNow();\n }\n\n function bindWindow() {\n if (windowBound || typeof window === 'undefined') return;\n windowBound = true;\n window.addEventListener('online', retryNow);\n document.addEventListener('visibilitychange', onVisibilityChange);\n }\n\n function unbindWindow() {\n if (!windowBound) return;\n windowBound = false;\n window.removeEventListener('online', retryNow);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n }\n\n function startHeartbeat(socket: WebSocket) {\n const heartbeat = options.heartbeat;\n if (!heartbeat) return;\n heartbeatTimer = setInterval(() => {\n socket.send(heartbeat.message ?? 'ping');\n if (heartbeat.timeout && pongTimer === undefined) {\n pongTimer = setTimeout(() => {\n log('heartbeat timeout');\n // The close handshake may never finish on a dead link, so don't wait for it.\n detach(socket, false);\n socket.close(4000, 'heartbeat timeout');\n handleClose({ code: 4000, reason: 'heartbeat timeout', wasClean: false });\n }, heartbeat.timeout);\n }\n }, heartbeat.interval);\n }\n\n function stopHeartbeat() {\n clearInterval(heartbeatTimer);\n clearTimeout(pongTimer);\n heartbeatTimer = pongTimer = undefined;\n }\n\n /** Stop tracking `socket`. Its eventual close event is still reported unless `reportClose` is false. */\n function detach(socket: WebSocket, reportClose: boolean) {\n if (ws === socket) ws = null;\n socket.onopen = socket.onmessage = socket.onerror = null;\n socket.onclose = reportClose\n ? event => emit('close', { code: event.code, reason: event.reason, wasClean: event.wasClean })\n : null;\n }\n\n function backoff(attempt: number) {\n const { minDelay, maxDelay, factor, jitter } = retry!;\n const base = Math.min(maxDelay, minDelay * factor ** (attempt - 1));\n return Math.round(base * (1 - jitter * Math.random()));\n }\n\n function open() {\n clearTimeout(retryTimer);\n retryTimer = undefined;\n const Impl = getImpl();\n if (!Impl) return;\n const id = ++generation;\n set({ status: snapshot.attempt === 0 ? 'connecting' : 'reconnecting' });\n\n let target: string | Promise<string>;\n try {\n target = typeof url === 'string' ? url : url();\n } catch (error) {\n urlFailed(error);\n return;\n }\n if (typeof target === 'string') {\n start(Impl, target);\n return;\n }\n Promise.resolve(target).then(\n resolved => {\n if (id === generation && wanted) start(Impl, resolved);\n },\n error => {\n if (id === generation && wanted) urlFailed(error);\n }\n );\n }\n\n /** `url()` threw or rejected (e.g. a token refresh failed): count it as a failed attempt. */\n function urlFailed(error: unknown) {\n const reason = error instanceof Error ? error : new Error(String(error));\n log('url() failed', reason);\n emit('error', reason);\n retryOrFail({ code: 1006, reason: 'url() failed', wasClean: false }, reason);\n }\n\n function start(Impl: typeof WebSocket, target: string) {\n let socket: WebSocket;\n try {\n socket = new Impl(target, options.protocols);\n } catch (error) {\n // e.g. an invalid URL; retrying won't help.\n emit('error', error as Error);\n fail(error);\n return;\n }\n if (options.binaryType) socket.binaryType = options.binaryType;\n ws = socket;\n log('connecting', target);\n\n socket.onopen = event => {\n log('open');\n opened = true;\n set({ status: 'open', attempt: 0 });\n startHeartbeat(socket);\n ready?.resolve();\n // Nobody holds it (it was started by reading `ready`, or the last holder left while\n // connecting): close it unless a holder turns up soon.\n if (refs === 0 && !pinned) {\n clearTimeout(teardownTimer);\n teardownTimer = setTimeout(teardown, READY_GRACE);\n }\n // `open` listeners go first, so a handshake sent from `onOpen` (e.g. auth) precedes\n // whatever was queued while disconnected.\n emit('open', event);\n if (ws !== socket) return; // a listener closed or replaced it\n const queued = pending;\n pending = [];\n for (const { data } of queued) socket.send(data);\n };\n socket.onmessage = event => receive(event, socket);\n socket.onerror = event => emit('error', event);\n socket.onclose = event => {\n detach(socket, false);\n handleClose({ code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function handleClose(info: CloseInfo) {\n stopHeartbeat();\n log('closed', info);\n retryOrFail(info);\n emit('close', info);\n }\n\n function retryOrFail(info: CloseInfo, error?: Error) {\n if (\n wanted &&\n retry &&\n snapshot.attempt < retry.maxAttempts &&\n (retry.shouldReconnect?.(info) ?? true)\n ) {\n const attempt = snapshot.attempt + 1;\n const delay = backoff(attempt);\n set({ status: 'reconnecting', attempt });\n log(`reconnecting in ${delay}ms (attempt ${attempt})`);\n retryTimer = setTimeout(open, delay);\n } else {\n fail(\n error ??\n new Error(`WebSocket closed (code ${info.code}${info.reason ? `: ${info.reason}` : ''})`)\n );\n }\n }\n\n function fail(reason: unknown) {\n wanted = false;\n opened = false;\n unbindWindow();\n pending = [];\n set({ status: 'closed' });\n rejectReady(reason);\n }\n\n function receive(event: MessageEvent, socket: WebSocket) {\n clearTimeout(pongTimer);\n pongTimer = undefined;\n if (options.heartbeat?.pong !== undefined && event.data === options.heartbeat.pong) return;\n\n // Async schema validation must not reorder messages.\n const run = () => decode(event, socket);\n if (inbox) {\n // One failed delivery must not stop the chain, or every later message is dropped.\n const next: Promise<void> = inbox\n .then(run)\n .catch(rethrowAsync)\n .then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n return;\n }\n const result = run();\n if (result) {\n const next: Promise<void> = result.catch(rethrowAsync).then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n }\n }\n\n function decode(event: MessageEvent, socket: WebSocket): void | Promise<void> {\n let value: unknown;\n try {\n value = options.parse\n ? options.parse(event.data)\n : options.json\n ? JSON.parse(event.data as string)\n : event.data;\n } catch (cause) {\n emit('error', new MessageError('Failed to parse message', event.data, { cause }));\n return;\n }\n\n const schema = options.schema;\n if (!schema) return deliver(value as In, event, socket);\n\n let result: ReturnType<(typeof schema)['~standard']['validate']>;\n try {\n result = schema['~standard'].validate(value);\n } catch (cause) {\n emit('error', new MessageError('Schema validation threw', event.data, { cause }));\n return;\n }\n if (isThenable<StandardSchemaResult<In>>(result)) {\n return Promise.resolve(result).then(\n r => validated(r, event, socket),\n cause => emit('error', new MessageError('Schema validation threw', event.data, { cause }))\n );\n }\n validated(result, event, socket);\n }\n\n function validated(result: StandardSchemaResult<In>, event: MessageEvent, socket: WebSocket) {\n if (result.issues) {\n emit(\n 'error',\n new MessageError('Message failed schema validation', event.data, { issues: result.issues })\n );\n } else {\n deliver(result.value, event, socket);\n }\n }\n\n function deliver(message: In, event: MessageEvent, socket: WebSocket) {\n if (ws !== socket) return; // closed or replaced while validating\n set({ lastMessage: message });\n emit('message', message, event);\n }\n\n function send(message: Out, sendOptions: SendOptions = {}): boolean {\n const data = options.serialize\n ? options.serialize(message)\n : options.json\n ? JSON.stringify(message)\n : (message as SendData);\n const { key, priority, maxBuffered } = sendOptions;\n if (ws && ws.readyState === OPEN) {\n // A late frame is worse than none: let a congested buffer drain instead of growing it.\n if (maxBuffered !== undefined && ws.bufferedAmount > maxBuffered) {\n log('dropped message: send buffer above maxBuffered');\n return false;\n }\n ws.send(data);\n return true;\n }\n if (queueLimit === 0 || sendOptions.volatile) {\n log('dropped message: socket is not open');\n return false;\n }\n if (!getImpl()) {\n // e.g. during a server render: this client can never connect, so don't hold on to it.\n log('dropped message: no WebSocket implementation available');\n return false;\n }\n if (key !== undefined) {\n pending = pending.filter(entry => {\n if (entry.key !== key) return true;\n dropped(entry);\n return false;\n });\n }\n let head = pending.findIndex(entry => !entry.priority);\n if (head < 0) head = pending.length;\n const entry = { data, key, priority, onDrop: sendOptions.onDrop };\n if (priority) pending.splice(head++, 0, entry);\n else pending.push(entry);\n if (pending.length > queueLimit) {\n // The oldest ordinary message goes first; priority ones only when nothing else is left.\n dropped(pending.splice(head < pending.length ? head : 0, 1)[0]!);\n log(`dropped oldest queued message: queue limit (${queueLimit}) reached`);\n }\n return false;\n }\n\n function dropped(entry: (typeof pending)[number]) {\n try {\n entry.onDrop?.();\n } catch (error) {\n rethrowAsync(error);\n }\n }\n\n function begin() {\n wanted = true;\n // Starting over after `close()` or giving up: wait for a new connection.\n if (snapshot.status === 'idle' || snapshot.status === 'closed') {\n opened = false;\n if (ready?.settled) ready = null;\n }\n snapshot = { ...snapshot, attempt: 0 }; // open() notifies\n bindWindow();\n open();\n }\n\n /** Start connecting unless already wanted. Used by holders (`acquire`, `ready`). */\n function ensureConnecting() {\n if (wanted || !getImpl()) return;\n begin();\n }\n\n function connect() {\n pinned = true;\n ensureConnecting();\n }\n\n function stop(code?: number, reason?: string) {\n wanted = false;\n generation++;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n unbindWindow();\n pending = [];\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(code, reason);\n }\n }\n\n function close(code = 1000, reason?: string) {\n pinned = false;\n opened = false;\n stop(code, reason);\n set({ status: 'closed', attempt: 0 });\n rejectReady(new Error('WebSocket was closed'));\n }\n\n function reconnect() {\n if (!getImpl()) return;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(1000, 'reconnect');\n }\n begin();\n }\n\n function teardown() {\n if (refs > 0 || pinned) return;\n // Someone may be suspended on `ready`; let the attempt finish.\n if (ready && !ready.settled) return;\n stop();\n ready = null;\n opened = false;\n set({ status: 'idle', attempt: 0 });\n onTeardown?.();\n }\n\n function acquire() {\n refs++;\n clearTimeout(teardownTimer);\n if (snapshot.status === 'idle') ensureConnecting();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--refs > 0) return;\n // Deferred so StrictMode's unmount/remount and route transitions don't churn the socket.\n clearTimeout(teardownTimer);\n teardownTimer = setTimeout(teardown, 0);\n };\n }\n\n return {\n url,\n get ready() {\n if (!getImpl()) {\n if (!unavailable) {\n unavailable = createDeferred();\n unavailable.reject(\n new Error('react-websocket: no WebSocket available here (server render?)')\n );\n }\n return unavailable.promise;\n }\n if (snapshot.status === 'idle' && !startScheduled) {\n // `ready` is read during render; start outside of it.\n startScheduled = true;\n queueMicrotask(() => {\n startScheduled = false;\n if (snapshot.status === 'idle') ensureConnecting();\n });\n }\n if (!ready) {\n ready = createDeferred();\n if (opened) ready.resolve();\n }\n return ready.promise;\n },\n get socket() {\n return ws;\n },\n subscribe(listener) {\n storeListeners.add(listener);\n return () => {\n storeListeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n on(type, listener) {\n // Wrap so the same function can be subscribed twice and unsubscribed independently.\n const entry = ((...args: unknown[]) =>\n (listener as (...a: unknown[]) => void)(...args)) as typeof listener;\n listeners[type].add(entry);\n return () => {\n listeners[type].delete(entry);\n };\n },\n send,\n connect,\n close,\n reconnect,\n acquire\n };\n}\n\n/**\n * Create a WebSocket client, usually at module level, to share across components.\n *\n * Nothing connects until a hook uses it, `ready` is read, or `connect()` is called.\n * It closes one tick after the last hook unmounts, unless `connect()` was called.\n *\n * @param url - A URL, or a function (sync or async) called before every connection\n * attempt, e.g. to put a fresh auth token in the URL on each reconnect.\n * @typeParam In - Type of incoming messages. Inferred from `options.schema` if given.\n * @typeParam Out - Type accepted by `send()`.\n *\n * @example\n * ```ts\n * type ChatIn = { user: string; text: string };\n * type ChatOut = { text: string };\n *\n * export const chat = createWebSocket<ChatIn, ChatOut>('wss://api.example.com/chat', { json: true });\n * ```\n */\nexport function createWebSocket<In = unknown, Out = unknown>(\n url: UrlSource,\n options?: WebSocketOptions<In, Out>\n): WebSocketClient<In, Out> {\n return createClient(url, options);\n}\n","import type { WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketLatency}: how pings and pongs look on the wire. */\nexport interface WebSocketLatencyOptions<In, Out> {\n /** The ping message, tagged with `id`. Sent with `volatile`, so pings are never queued. */\n ping: (id: number) => Out;\n /**\n * Recognize a pong: return the `id` of the ping it answers, and the server's clock\n * (`Date.now()` on the server, in ms) when it replied. Return `undefined` (or `null`)\n * for any other message. Without `time`, only the round-trip time is measured.\n */\n pong: (message: In) => { id: number | string; time?: number } | null | undefined;\n /**\n * How often to ping while open, in ms. The first ping goes out as soon as the socket opens.\n * @default 2000\n */\n interval?: number;\n /**\n * How many recent measurements to keep. `rtt` is their median, and `offset` comes from\n * the one with the lowest round trip, the most accurate estimate.\n * @default 5\n */\n samples?: number;\n}\n\n/** Latest latency measurements. A new object is created on every change. */\nexport interface Latency {\n /** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */\n readonly rtt: number | undefined;\n /**\n * Estimated server clock minus local clock, in ms. Add it to `Date.now()` for server time.\n * `undefined` until a pong carries `time`.\n */\n readonly offset: number | undefined;\n}\n\n/** Round-trip time and server clock offset for one client. Create with {@link createWebSocketLatency}. */\nexport interface WebSocketLatency {\n /** The client being measured. Hooks reading the latency keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /** The current {@link Latency}. Returns the same object until it changes. */\n getSnapshot(): Latency;\n /** Called whenever a measurement changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** The estimated server time: `Date.now() + offset`, or `Date.now()` before any estimate. */\n serverNow(): number;\n /** Ping now instead of waiting for the next interval. Does nothing unless the socket is open. */\n ping(): void;\n /** Stop pinging and listening. Only needed for instances created dynamically. */\n dispose(): void;\n}\n\nconst EMPTY: Latency = Object.freeze({ rtt: undefined, offset: undefined });\n\nfunction median(values: number[]) {\n const sorted = [...values].sort((a, b) => a - b);\n const middle = sorted.length >> 1;\n return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;\n}\n\n/**\n * Measure round-trip time and estimate the server's clock, for ping displays, countdowns\n * and timestamps that must agree across players.\n *\n * Pings are sent on an interval while the socket is open, and paused otherwise. Measurements\n * from a previous connection are discarded on reconnect, but the last values stay readable\n * until new ones arrive. It doesn't open the connection by itself.\n *\n * Pongs are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * export const latency = createWebSocketLatency(game, {\n * ping: id => ({ type: 'ping', id }),\n * pong: message => (message.type === 'pong' ? { id: message.id, time: message.time } : undefined)\n * });\n *\n * // In a component:\n * const { rtt } = useWebSocketLatency(latency);\n *\n * // Anywhere: seconds left in a round that ends at the server's `endsAt`.\n * const left = (endsAt - latency.serverNow()) / 1000;\n * ```\n */\n// `const` + `NoInfer`: take `In` and `Out` from the client only, and keep literals such as\n// `type: 'ping'` from widening to `string` inside the callbacks.\nexport function createWebSocketLatency<In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>\n): WebSocketLatency {\n const interval = options.interval ?? 2000;\n const keep = Math.max(1, options.samples ?? 5);\n const listeners = new Set<() => void>();\n let snapshot = EMPTY;\n // Ping id -> `performance.now()` when sent. Pongs that never come are evicted oldest first.\n const inFlight = new Map<string, number>();\n let samples: { rtt: number; offset: number | undefined }[] = [];\n let nextId = 0;\n let timer: ReturnType<typeof setInterval> | undefined;\n\n function ping() {\n if (client.getSnapshot().status !== 'open') return;\n const id = ++nextId;\n inFlight.set(String(id), performance.now());\n if (inFlight.size > keep * 2) inFlight.delete(inFlight.keys().next().value!);\n client.send(options.ping(id), { volatile: true });\n }\n\n function start() {\n stop();\n inFlight.clear();\n samples = [];\n ping();\n timer = setInterval(ping, interval);\n }\n\n function stop() {\n clearInterval(timer);\n timer = undefined;\n }\n\n function measure(id: string, serverTime: number | undefined) {\n const sentAt = inFlight.get(id);\n if (sentAt === undefined) return;\n inFlight.delete(id);\n const rtt = performance.now() - sentAt;\n // The server read its clock about halfway through the round trip.\n const offset = serverTime === undefined ? undefined : serverTime + rtt / 2 - Date.now();\n samples.push({ rtt, offset });\n if (samples.length > keep) samples.shift();\n\n let best: (typeof samples)[number] | undefined;\n for (const sample of samples) {\n if (sample.offset !== undefined && (!best || sample.rtt < best.rtt)) best = sample;\n }\n snapshot = {\n rtt: median(samples.map(sample => sample.rtt)),\n offset: best ? best.offset : snapshot.offset\n };\n for (const listener of [...listeners]) listener();\n }\n\n const offs = [\n client.on('open', start),\n client.on('message', message => {\n const pong = options.pong(message);\n if (pong != null) measure(String(pong.id), pong.time);\n }),\n client.subscribe(() => {\n if (client.getSnapshot().status !== 'open') stop();\n })\n ];\n if (client.getSnapshot().status === 'open') start();\n\n return {\n client,\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n serverNow: () => Date.now() + (snapshot.offset ?? 0),\n ping,\n dispose() {\n stop();\n offs.forEach(off => off());\n }\n };\n}\n","import type { SendOptions, WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketRequests}: how requests and replies look on the wire. */\nexport interface WebSocketRequestsOptions<Req, In, Out> {\n /**\n * Build the outgoing message for `request(message)`, tagged with `id`. Annotate `message`\n * to type what `request()` accepts.\n */\n send: (message: Req, id: number) => Out;\n /**\n * The id an incoming message replies to, or `undefined` (or `null`) if it isn't a reply.\n * A string id matches the number it was sent as, so either echo works.\n */\n reply: (message: In) => number | string | null | undefined;\n /**\n * Called on a reply. Return something other than `undefined` to reject the request with\n * it instead of resolving, e.g. for a server-side error reply. A stream throws it.\n */\n error?: (message: In) => unknown;\n /**\n * Whether a reply is the last one of a stream. `stream()` needs it. That reply is yielded\n * too, then the stream ends.\n */\n done?: (message: In) => boolean;\n /**\n * Build the message that tells the server to stop working on request `id`. Sent when this\n * side gives up: the request's `signal` aborts, it times out, a loop over a stream exits\n * early, or the manager is disposed. Not sent after the last reply, an error reply, a lost\n * connection or `close()`.\n */\n cancel?: (id: number) => Out;\n /**\n * Default time to wait for a reply, in ms. For a stream, the time to wait for each reply,\n * including the first. `Infinity` waits forever.\n * @default 10000\n */\n timeout?: number;\n}\n\n/** Per-call options for {@link WebSocketRequests.request} and {@link WebSocketRequests.stream}. */\nexport interface RequestOptions extends SendOptions {\n /**\n * Time to wait for a reply (for a stream, for each reply), in ms. Overrides the manager's\n * `timeout`.\n */\n timeout?: number;\n /** Abort the request. It rejects (a stream throws) with `signal.reason`. A late reply is ignored. */\n signal?: AbortSignal;\n}\n\n/** Request/response over one client. Create with {@link createWebSocketRequests}. */\nexport interface WebSocketRequests<Req, In> {\n /** The client requests are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Send a request and resolve with its reply. Holds the connection until it settles.\n *\n * Rejects with a `TimeoutError` `DOMException` after `timeout`, with `signal.reason` when\n * aborted, and with an `Error` when the connection it was sent on closes (the reply can\n * no longer arrive) or the client stops. A request made while disconnected is queued like\n * any other message and waits for the connection; it rejects if it is dropped from the\n * queue (replaced by a newer request with the same `key`, or evicted by `queue.limit`).\n */\n request(message: Req, options?: RequestOptions): Promise<In>;\n /**\n * Send a request and iterate over its replies, up to and including the one `done` matches.\n * Holds the connection until the stream ends. Needs the `done` option.\n *\n * `timeout` is the time to wait for each reply. Replies that arrive before the loop reads\n * them are buffered. The stream is one-shot: iterate it once.\n *\n * Fails where `request()` rejects, with the same errors, after yielding the replies already\n * received. Aborting `signal` throws `signal.reason` right away and discards them. Leaving\n * the loop early, aborting and timing out send `cancel`.\n *\n * @example\n * ```ts\n * for await (const reply of rpc.stream({ type: 'ask', prompt }, { signal })) {\n * text += reply.delta;\n * }\n * ```\n */\n stream(message: Req, options?: RequestOptions): AsyncIterableIterator<In>;\n /** Number of requests and streams waiting for a reply. */\n pending(): number;\n /** Reject every pending request and stop listening. Only needed for managers created dynamically. */\n dispose(): void;\n}\n\n// Last id sent per client, shared by its managers so two of them never send the same id\n// and resolve each other's requests with one reply.\nconst lastIds = new WeakMap<WebSocketClient<any, any>, number>();\n\nconst VOLATILE = { volatile: true };\nconst noop = () => {};\n\ninterface Pending<In> {\n /** The socket the request went out on, or `null` while it waits in the client's queue. */\n socket: WebSocket | null;\n /** A reply that isn't an error. */\n receive(reply: In): void;\n /** Settle, failed with `reason` or not. `cancel` tells the server to stop. Only the first call counts. */\n end(failed: boolean, reason?: unknown, cancel?: boolean): void;\n}\n\n/**\n * Send requests and await their replies, matched by an id the library generates.\n *\n * Replies are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * type Request = { type: 'join'; room: string } | { type: 'leave' };\n *\n * export const rpc = createWebSocketRequests(game, {\n * send: (message: Request, id) => ({ ...message, id }),\n * reply: message => (message.type === 'reply' ? message.id : undefined),\n * error: message => (message.type === 'reply' && message.error ? new Error(message.error) : undefined)\n * });\n *\n * const reply = await rpc.request({ type: 'join', room: 'lobby' }, { timeout: 5000 });\n * ```\n */\n// `const` + `NoInfer`: `In` and `Out` come from the client only, with literals kept unwidened;\n// `Req` comes from how `send` annotates its parameter.\nexport function createWebSocketRequests<Req, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>\n): WebSocketRequests<Req, In> {\n const waiting = new Map<string, Pending<In>>();\n\n function endWhere(\n test: (entry: Pending<In>) => boolean,\n reason: () => unknown,\n cancel?: boolean\n ) {\n for (const entry of [...waiting.values()]) if (test(entry)) entry.end(true, reason(), cancel);\n }\n\n const offs = [\n client.on('message', message => {\n const id = options.reply(message);\n const entry = id == null ? undefined : waiting.get(String(id));\n if (!entry) return;\n const error = options.error?.(message);\n if (error === undefined) entry.receive(message);\n else entry.end(true, error);\n }),\n // `open` listeners run before the client flushes its queue: queued requests go out on this socket.\n client.on('open', () => {\n for (const entry of waiting.values()) entry.socket ??= client.socket;\n }),\n client.subscribe(() => {\n const { status } = client.getSnapshot();\n if (status === 'closed' || status === 'idle') {\n // The queue was cleared too, so nothing still waiting can be sent.\n endWhere(\n () => true,\n () => new Error('WebSocket was closed before the request was answered')\n );\n } else {\n endWhere(\n entry => entry.socket !== null && entry.socket !== client.socket,\n () => new Error('WebSocket connection was lost before the request was answered')\n );\n }\n })\n ];\n\n /**\n * Send `message` as a new request. `next` gets each reply that isn't an error and returns\n * whether it was the last; `done` runs once, when the request ends. Returns a function that\n * ends it from this side and tells the server.\n */\n function start(\n message: Req,\n requestOptions: RequestOptions,\n next: (reply: In) => boolean,\n done: (failed: boolean, reason?: unknown) => void\n ): () => void {\n const { signal, priority } = requestOptions;\n if (signal?.aborted) {\n done(true, signal.reason);\n return noop;\n }\n\n const id = (lastIds.get(client) ?? 0) + 1;\n lastIds.set(client, id);\n const key = String(id);\n const timeout = requestOptions.timeout ?? options.timeout ?? 10_000;\n const release = client.acquire();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => entry.end(true, signal!.reason, true);\n\n function arm() {\n clearTimeout(timer);\n if (timeout > 0 && timeout < Infinity) {\n timer = setTimeout(\n () =>\n entry.end(\n true,\n new DOMException(`Request ${id} timed out after ${timeout}ms`, 'TimeoutError'),\n true\n ),\n timeout\n );\n }\n }\n\n const entry: Pending<In> = {\n socket: null,\n receive(reply) {\n if (next(reply)) entry.end(false);\n else arm();\n },\n end(failed, reason, cancel) {\n if (!waiting.delete(key)) return;\n clearTimeout(timer);\n signal?.removeEventListener('abort', onAbort);\n release();\n done(failed, reason);\n if (cancel && options.cancel) {\n try {\n // Still queued, it can't be taken back: queue the cancel right behind it. Once sent,\n // the cancel only means something on that connection, so drop it unless it's open.\n client.send(options.cancel(id), entry.socket ? VOLATILE : { priority });\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n };\n waiting.set(key, entry);\n signal?.addEventListener('abort', onAbort, { once: true });\n arm();\n\n const { status } = client.getSnapshot();\n if (status === 'closed' || status === 'idle') {\n // Closed until someone reconnects it, or (idle after acquiring) it can't connect here.\n entry.end(true, new Error(`WebSocket is ${status}: request not sent`));\n } else {\n try {\n const sent = client.send(options.send(message, id), {\n ...requestOptions,\n onDrop() {\n entry.end(\n true,\n new Error('Request was dropped from the send queue before it was sent')\n );\n requestOptions.onDrop?.();\n }\n });\n if (sent) entry.socket = client.socket;\n // Open but not sent: `maxBuffered` dropped it, and nothing will send it later.\n else if (client.socket?.readyState === 1)\n entry.end(true, new Error('WebSocket send buffer is full: request dropped'));\n else if (requestOptions.volatile)\n entry.end(true, new Error('WebSocket is not open: request dropped'));\n } catch (error) {\n entry.end(true, error);\n }\n }\n return () => entry.end(false, undefined, true);\n }\n\n return {\n client,\n request(message, requestOptions = {}) {\n return new Promise<In>((resolve, reject) => {\n start(\n message,\n requestOptions,\n reply => {\n resolve(reply);\n return true;\n },\n (failed, reason) => {\n if (failed) reject(reason);\n }\n );\n });\n },\n stream(message, requestOptions = {}) {\n const last = options.done;\n if (!last) throw new TypeError('stream() needs the `done` option');\n const replies: In[] = [];\n let ended: [failed: boolean, reason: unknown] | undefined;\n let wake = noop;\n const stop = start(\n message,\n requestOptions,\n reply => {\n replies.push(reply);\n wake();\n return last(reply);\n },\n (failed, reason) => {\n // Aborting stops right away; any other end comes after the replies already received.\n if (requestOptions.signal?.aborted) replies.length = 0;\n ended = [failed, reason];\n wake();\n }\n );\n\n async function* read() {\n try {\n for (;;) {\n if (replies.length) yield replies.shift()!;\n else if (ended) {\n if (ended[0]) throw ended[1];\n return;\n } else await new Promise<void>(resolve => (wake = resolve));\n }\n } finally {\n stop();\n }\n }\n\n const iterator = read();\n const close = iterator.return;\n // A generator closed before its first `next()` skips `finally`, and one closed during a\n // `next()` waits for it: stop first, so leaving a loop tells the server right away.\n iterator.return = value => {\n stop();\n return close.call(iterator, value);\n };\n return iterator;\n },\n pending: () => waiting.size,\n dispose() {\n offs.forEach(off => off());\n endWhere(\n () => true,\n () => new Error('Requests were disposed'),\n true\n );\n }\n };\n}\n","import type { WebSocketClient } from './types';\n\n/** What `request` returns for a request: any object with these fields, such as the message itself. */\ntype RequestFields = { id: number | string; method: string; params?: unknown; timeout?: number };\n\n/**\n * The type of `params` in `Q`, keeping `undefined` when they're optional and giving `undefined`\n * when there are none. (Inferring `params?: P` directly would drop the `undefined`.)\n */\ntype ParamsOf<Q> = Q extends unknown\n ? 'params' extends keyof Q\n ? Q['params' & keyof Q]\n : undefined\n : never;\n\n/**\n * Options for {@link createWebSocketResponder}: how the server's requests and your replies look\n * on the wire.\n *\n * @typeParam Q - What `request` returns. Handlers receive its `params`.\n * @typeParam R - What handlers return, from the annotation on `respond`'s `result`.\n */\nexport interface WebSocketResponderOptions<Q extends RequestFields, R, In, Out> {\n /**\n * Recognize a request from the server: its `id`, the `method` handlers are registered for,\n * and the `params` they receive. Return `undefined` (or `null`) for any other message.\n * A `timeout` (in ms) overrides the manager's for this request.\n *\n * `params` come from the server, so validate them before acting on them.\n */\n request: (message: In) => Q | null | undefined;\n /** Build the reply to request `id`. Annotate `result` to type what handlers return. */\n respond: (id: number | string, result: R) => Out;\n /**\n * Build the error reply to request `id`: what a handler threw, a `NotFoundError` `DOMException`\n * when nothing is registered for the method, a `TimeoutError` after `timeout`, or an\n * `AbortError` from `dispose()`.\n */\n error: (id: number | string, error: unknown) => Out;\n /**\n * The id of a request the server withdrew, or `undefined` (or `null`) if the message isn't a\n * cancellation. The request's `signal` aborts and nothing is sent.\n */\n cancel?: (message: In) => number | string | null | undefined;\n /**\n * Time to answer a request, in ms. When it runs out, the `error` reply (a `TimeoutError`)\n * is sent and the request's `signal` aborts.\n * @default Infinity\n */\n timeout?: number;\n}\n\n/** A request from the server that hasn't been answered yet. */\nexport interface IncomingRequest<P = unknown, R = unknown> {\n /** The id the server sent. Replies carry it back. */\n readonly id: number | string;\n /** The method it was sent for. */\n readonly method: string;\n /** The `params` from `request`. They come from the server, so validate them. */\n readonly params: P;\n /**\n * Aborts when the answer is no longer wanted: the server cancelled the request, it timed out,\n * the connection it arrived on closed, the responder was disposed, or it was answered with\n * `respond` or `reject` while its handler was still running.\n */\n readonly signal: AbortSignal;\n /**\n * Reply with `result`. Only the first answer counts.\n * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.\n */\n respond(result: R): boolean;\n /**\n * Reply with an error, built by the `error` option. Only the first answer counts.\n * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.\n */\n reject(error: unknown): boolean;\n}\n\n/**\n * Answers a request in code. Return (or resolve) the result to reply with it; throw (or reject)\n * to send the `error` reply instead.\n */\nexport type RequestHandler<P = unknown, R = unknown> = (\n params: P,\n request: IncomingRequest<P, R>\n) => R | PromiseLike<R>;\n\n/** Answers the server's requests on one client. Create with {@link createWebSocketResponder}. */\nexport interface WebSocketResponder<P = unknown, R = unknown> {\n /** The client requests arrive on. Hooks reading the responder keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Answer requests for `method` until the returned function is called.\n *\n * With a `handler`, requests are answered in code. Without one, they wait in\n * {@link getSnapshot} until something calls `respond` or `reject` on them, e.g. a dialog\n * that asks the user. When several registrations exist for one method, the newest one takes\n * new requests, and unregistering it hands them back to the previous one. Requests for a\n * method with no registration get a `NotFoundError` reply.\n *\n * @returns An unregister function (safe to call more than once). Requests already waiting stay.\n */\n onRequest(method: string, handler?: RequestHandler<P, R>): () => void;\n /**\n * Requests waiting for an answer from outside a handler, oldest first. Returns the same array\n * until it changes.\n */\n getSnapshot(): readonly IncomingRequest<P, R>[];\n /** Called whenever {@link getSnapshot} changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /**\n * Stop answering: send an `AbortError` reply to every request in flight and stop listening.\n * Only needed for responders created dynamically.\n */\n dispose(): void;\n}\n\ninterface Entry {\n /** The socket the request arrived on. Its reply can only go back on that one. */\n readonly socket: WebSocket | null;\n /** Forget the request and abort its signal, without replying. */\n drop(reason: DOMException): void;\n /** Forget the request, abort its signal and send the `error` reply, both with `error`. */\n fail(error: DOMException): void;\n}\n\nconst VOLATILE = { volatile: true };\nconst abortError = (message: string) => new DOMException(message, 'AbortError');\n\n/**\n * Answer requests the server sends: run a handler for tools that only exist in the browser\n * (selection, clipboard, geolocation), or let a person answer, e.g. to approve an agent's action.\n * The reverse of `createWebSocketRequests`.\n *\n * Every request gets exactly one reply while its connection lives: the handler's result, an\n * `error` reply when it throws, has no registration or times out. When the connection a request\n * arrived on closes, the request is dropped and nothing is sent, since the server can't match a\n * reply on a new connection. Replies are never queued.\n *\n * Requests are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.\n *\n * @example\n * ```ts\n * export const tools = createWebSocketResponder(agent, {\n * request: message => (message.type === 'call' ? message : undefined),\n * respond: (id, result: unknown) => ({ type: 'result', id, result }),\n * error: (id, error) => ({ type: 'result', id, error: String(error) })\n * });\n *\n * tools.onRequest('get_selection', () => window.getSelection()?.toString() ?? '');\n *\n * // In a component: requests a person answers.\n * const approvals = useAgentApproval(tools, 'approve');\n * approvals[0]?.respond({ approved: true });\n * ```\n */\n// `const` + `NoInfer`: `In` and `Out` come from the client only, with literals kept unwidened;\n// `Q` comes from what `request` returns and `R` from how `respond` annotates `result`.\nexport function createWebSocketResponder<Q extends RequestFields, R, In, const Out>(\n client: WebSocketClient<In, Out>,\n options: WebSocketResponderOptions<Q, R, NoInfer<In>, NoInfer<Out>>\n): WebSocketResponder<ParamsOf<Q>, R> {\n type P = ParamsOf<Q>;\n const entries = new Map<string, Entry>();\n const registrations = new Map<string, { handler?: RequestHandler<P, R> }[]>();\n const listeners = new Set<() => void>();\n let waiting: readonly IncomingRequest<P, R>[] = [];\n\n function setWaiting(next: readonly IncomingRequest<P, R>[]) {\n waiting = next;\n for (const listener of [...listeners]) listener();\n }\n\n /** Send a reply, or an `error` reply if building or encoding it throws. */\n function reply(id: number | string, build: () => Out): boolean {\n try {\n return client.send(build(), VOLATILE);\n } catch (error) {\n return client.send(options.error(id, error), VOLATILE);\n }\n }\n\n function receive(incoming: Q) {\n const { id, method } = incoming;\n const key = String(id);\n if (entries.has(key)) return; // sent again while it is being answered\n const registration = registrations.get(method)?.at(-1);\n if (!registration) {\n const error = new DOMException(`No handler for request method \"${method}\"`, 'NotFoundError');\n reply(id, () => options.error(id, error));\n return;\n }\n\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let done = false;\n let running = false;\n\n function settle(build: (() => Out) | null, reason?: unknown) {\n if (done) return false;\n done = true;\n entries.delete(key);\n clearTimeout(timer);\n if (waiting.includes(request)) setWaiting(waiting.filter(entry => entry !== request));\n if (reason !== undefined) controller.abort(reason);\n return build ? reply(id, build) : false;\n }\n\n // An answer from outside the handler makes the handler's work moot.\n const answeredElsewhere = () =>\n running ? abortError(`Request ${id} was answered elsewhere`) : undefined;\n const request: IncomingRequest<P, R> = {\n id,\n method,\n params: incoming.params as P,\n signal: controller.signal,\n respond: result => settle(() => options.respond(id, result), answeredElsewhere()),\n reject: error => settle(() => options.error(id, error), answeredElsewhere())\n };\n const fail = (error: DOMException) => {\n settle(() => options.error(id, error), error);\n };\n // Registered before the handler runs, so a handler that closes the socket drops its own request.\n entries.set(key, {\n socket: client.socket,\n drop: reason => {\n settle(null, reason);\n },\n fail\n });\n\n const timeout = incoming.timeout ?? options.timeout ?? Infinity;\n if (timeout > 0 && timeout < Infinity) {\n timer = setTimeout(\n () =>\n fail(\n new DOMException(`Request ${id} was not answered within ${timeout}ms`, 'TimeoutError')\n ),\n timeout\n );\n }\n\n const { handler } = registration;\n if (!handler) {\n setWaiting([...waiting, request]);\n return;\n }\n running = true;\n // Also catches a handler that throws synchronously.\n new Promise<R>(resolve => resolve(handler(request.params, request))).then(\n result => {\n running = false;\n request.respond(result);\n },\n error => {\n running = false;\n request.reject(error);\n }\n );\n }\n\n const offs = [\n client.on('message', message => {\n const incoming = options.request(message);\n if (incoming != null) {\n receive(incoming);\n return;\n }\n const id = options.cancel?.(message);\n if (id != null) {\n entries.get(String(id))?.drop(abortError(`Request ${id} was cancelled`));\n }\n }),\n // Every close, reconnect and teardown replaces `client.socket` and notifies.\n client.subscribe(() => {\n for (const entry of [...entries.values()]) {\n if (entry.socket !== client.socket) {\n entry.drop(abortError('WebSocket connection was lost before the request was answered'));\n }\n }\n })\n ];\n\n return {\n client,\n onRequest(method, handler) {\n let stack = registrations.get(method);\n if (!stack) registrations.set(method, (stack = []));\n const registration = { handler };\n stack.push(registration);\n return () => {\n const index = stack.indexOf(registration);\n if (index !== -1) stack.splice(index, 1);\n };\n },\n getSnapshot: () => waiting,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n offs.forEach(off => off());\n registrations.clear();\n for (const entry of [...entries.values()]) entry.fail(abortError('Responder was disposed'));\n }\n };\n}\n","import type { WebSocketLatency } from './latency';\nimport type { WebSocketClient } from './types';\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/** Options for {@link createWebSocketSendRate}. */\nexport interface WebSocketSendRateOptions {\n /**\n * Ticks per second while the connection keeps up.\n * @default 30\n */\n maxRate?: number;\n /**\n * The rate never drops below this, in ticks per second.\n * @default 5\n */\n minRate?: number;\n /**\n * Bytes waiting in the browser's send buffer (`socket.bufferedAmount`) above which a tick\n * sends nothing and the rate halves.\n * @default 1024\n */\n maxBuffered?: number;\n /**\n * Measurements from `createWebSocketLatency` on the same client. With them, a round-trip time\n * that rises also lowers the rate. Without them, only the send buffer is watched.\n */\n latency?: Pick<WebSocketLatency, 'getSnapshot'>;\n /**\n * How far `rtt` may rise above the lowest one measured on this connection before the rate\n * halves, in ms. A steady high ping keeps the full rate; only a rising one counts.\n * @default 100\n */\n maxRttIncrease?: number;\n}\n\n/** The current send rate. A new object is created on every change. */\nexport interface SendRate {\n /** Ticks per second, rounded. */\n readonly rate: number;\n /**\n * Whether the last tick found the link congested: the send buffer above `maxBuffered`, or\n * `rtt` risen more than `maxRttIncrease`.\n */\n readonly congested: boolean;\n}\n\n/** Keyed sends coalesced at a rate that adapts to the link. Create with {@link createWebSocketSendRate}. */\nexport interface WebSocketSendRate<Out> {\n /** The client the messages are sent on. */\n readonly client: WebSocketClient<any, Out>;\n /**\n * Send `message` at the next tick. A message with the same `key` still waiting for it is\n * replaced, so only the newest one goes out. Sent with `volatile`.\n */\n send(message: Out, key: string): void;\n /** Send everything waiting now, e.g. right before a one-shot action that must carry the latest aim. */\n flush(): void;\n /** The current {@link SendRate}. Returns the same object until it changes. */\n getSnapshot(): SendRate;\n /** Called whenever the rate or `congested` changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Stop sending and listening. Only needed for instances created dynamically. */\n dispose(): void;\n}\n\nconst VOLATILE = { volatile: true };\n\n/**\n * Send high-rate state, such as aim, cursor or position, at a rate that adapts to the\n * connection. Messages are coalesced per key between ticks. The rate drops by half when the\n * send buffer fills up or the round trip grows, and climbs back one tick per second at a time\n * when the link keeps up, so players on a poor connection degrade smoothly instead of building\n * up lag.\n *\n * Ticks run only while the socket is open and something is waiting. Messages waiting during a\n * reconnect go out after it; `close()` drops them. It doesn't open the connection by itself.\n *\n * @example\n * ```ts\n * export const stream = createWebSocketSendRate(game, { latency, maxRate: 30 });\n *\n * // On every pointer move: at most 30 a second, fewer on a congested link.\n * stream.send({ type: 'aim', angle }, 'aim');\n * ```\n */\nexport function createWebSocketSendRate<Out>(\n client: WebSocketClient<any, Out>,\n options: WebSocketSendRateOptions = {}\n): WebSocketSendRate<Out> {\n const { maxBuffered = 1024, latency, maxRttIncrease = 100 } = options;\n const maxRate = options.maxRate ?? 30;\n const minRate = Math.min(options.minRate ?? 5, maxRate);\n const listeners = new Set<() => void>();\n // Insertion order is send order: a replaced message moves to the end.\n const pending = new Map<string, Out>();\n let rate = maxRate;\n let snapshot: SendRate = { rate: maxRate, congested: false };\n let last = -Infinity; // `performance.now()` at the last tick\n let best = Infinity; // the lowest `rtt` on this connection\n let slow = false; // `rtt` has risen too far above `best`\n let measured: unknown; // the latency snapshot already reacted to\n let timer: Timer | undefined;\n let disposed = false;\n\n function flush() {\n for (const [key, message] of pending) {\n if (!client.send(message, VOLATILE)) return; // not open: keep the rest for later\n pending.delete(key);\n }\n }\n\n function publish(congested: boolean) {\n const rounded = Math.round(rate);\n if (rounded === snapshot.rate && congested === snapshot.congested) return;\n snapshot = { rate: rounded, congested };\n for (const listener of [...listeners]) listener();\n }\n\n function schedule() {\n if (disposed || timer !== undefined || !pending.size || client.getSnapshot().status !== 'open')\n return;\n // Right away after a pause, otherwise one interval after the last tick.\n timer = setTimeout(tick, Math.max(0, last + 1000 / rate - performance.now()));\n }\n\n function stop() {\n clearTimeout(timer);\n timer = undefined;\n }\n\n // Additive increase, multiplicative decrease, as TCP does.\n function tick() {\n timer = undefined;\n last = performance.now();\n const measurement = latency?.getSnapshot();\n if (measurement !== measured) {\n // React to each measurement once.\n measured = measurement;\n const rtt = measurement?.rtt;\n if (rtt !== undefined) {\n best = Math.min(best, rtt);\n slow = rtt - best > maxRttIncrease;\n if (slow) rate /= 2;\n }\n }\n // Checked once per tick, not per message, so messages in one tick don't count against each other.\n const full = (client.socket?.bufferedAmount ?? 0) > maxBuffered;\n if (full) rate /= 2;\n else {\n flush();\n if (!slow) rate++;\n }\n rate = Math.min(maxRate, Math.max(minRate, rate));\n publish(full || slow);\n schedule();\n }\n\n const offs = [\n client.on('open', () => {\n // A new connection may take a different route: measure its best round trip afresh, and\n // ignore the last connection's measurement, which stays readable until a new one arrives.\n best = Infinity;\n slow = false;\n measured = latency?.getSnapshot();\n schedule(); // after the client's own queue, which is sent once `open` listeners return\n }),\n client.subscribe(() => {\n const { status } = client.getSnapshot();\n if (status !== 'open') stop();\n // Like the client's queue: kept through a reconnect, dropped by `close()` or giving up.\n if (status === 'closed' || status === 'idle') pending.clear();\n })\n ];\n\n return {\n client,\n send(message, key) {\n pending.delete(key);\n pending.set(key, message);\n schedule();\n },\n flush,\n getSnapshot: () => snapshot,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n stop();\n pending.clear();\n offs.forEach(off => off());\n }\n };\n}\n","import type { WebSocketClient } from './types';\n\n/** Options for {@link createWebSocketState}. */\nexport interface WebSocketStateOptions<S, In> {\n /** The state before any message arrives, and what `reset()` returns to. */\n initialState: S;\n /**\n * Fold one incoming message into the state. Must be pure: return a new object for a\n * change, or the same `state` to ignore the message (subscribers aren't notified).\n */\n reduce: (state: S, message: In) => S;\n /**\n * `'frame'`: notify subscribers at most once per animation frame instead of once per\n * message, so a fast stream (tokens, tickers, game state) renders once per frame.\n * `getState()` is always current; only notifications wait. `setState` and `reset` still\n * notify right away.\n *\n * Browsers pause animation frames in background tabs: the state keeps up, and subscribers\n * hear about it when the tab is visible again. Without `requestAnimationFrame` (Node, some\n * workers), it waits about 16 ms instead.\n */\n batch?: 'frame';\n}\n\n/**\n * State derived from a client's messages. Read it with `useWebSocketState(store, selector)`,\n * or with `getState`/`subscribe` outside React.\n *\n * @typeParam S - The state type. Don't use a function type: `setState` treats functions as updaters.\n */\nexport interface WebSocketState<S> {\n /** The client whose messages this store reduces. Hooks reading the store keep it connected. */\n readonly client: WebSocketClient<any, any>;\n /** The `initialState` it was created with. Used for server rendering and hydration. */\n readonly initialState: S;\n /** The current state. Returns the same object until it changes. */\n getState(): S;\n /** Called whenever the state changes. Compatible with `useSyncExternalStore`. */\n subscribe(listener: () => void): () => void;\n /** Replace the state, or update it from the current one, e.g. for optimistic updates. */\n setState(update: S | ((state: S) => S)): void;\n /** Go back to `initialState`. */\n reset(): void;\n /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */\n dispose(): void;\n}\n\n/**\n * Keep state derived from a client's messages, like a reducer that runs on every message.\n * It starts listening immediately and keeps the state across reconnects; it doesn't open\n * the connection by itself.\n *\n * @example\n * ```ts\n * const prices = createWebSocket<Tick>('wss://api.example.com/prices', { json: true });\n *\n * export const priceState = createWebSocketState(prices, {\n * initialState: {} as Record<string, number>,\n * reduce: (state, tick) => ({ ...state, [tick.symbol]: tick.price })\n * });\n *\n * // In a component: re-renders only when ACME's price changes.\n * const acme = useWebSocketState(priceState, state => state.ACME);\n * ```\n */\nexport function createWebSocketState<S, In>(\n client: WebSocketClient<In, any>,\n // `In` comes from the client only, not from how `reduce` annotates its parameter.\n options: WebSocketStateOptions<S, NoInfer<In>>\n): WebSocketState<S> {\n const { initialState, reduce, batch } = options;\n let state = initialState;\n // What subscribers were last told about, so a frame that finds nothing new stays quiet.\n let notified = state;\n let frame = false;\n const listeners = new Set<() => void>();\n\n function notify() {\n if (Object.is(state, notified)) return;\n notified = state;\n for (const listener of [...listeners]) listener();\n }\n\n function flush() {\n frame = false;\n notify();\n }\n\n function update(change: S | ((state: S) => S), later?: boolean) {\n const next = typeof change === 'function' ? (change as (state: S) => S)(state) : change;\n if (Object.is(next, state)) return;\n state = next;\n if (!later) notify();\n else if (!frame) {\n frame = true;\n // Node and some workers have no animation frames: wait about one instead.\n if (typeof requestAnimationFrame === 'function') requestAnimationFrame(flush);\n else setTimeout(flush, 16);\n }\n }\n\n // A throwing reducer leaves the state unchanged; the client re-throws the error asynchronously.\n const off = client.on('message', message =>\n update(current => reduce(current, message), batch === 'frame')\n );\n\n return {\n client,\n initialState,\n getState: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n setState: change => update(change),\n reset: () => update(initialState),\n dispose: off\n };\n}\n","import type { WebSocketClient } from './types';\n\ntype Timer = ReturnType<typeof setTimeout>;\n\n/** Options for {@link createWebSocketTopics}: the messages your server expects. */\nexport interface WebSocketTopicsOptions<Out> {\n /** The message that subscribes to `topic`. */\n subscribe: (topic: string) => Out;\n /** The message that unsubscribes from `topic`. Omit it if your server has none. */\n unsubscribe?: (topic: string) => Out;\n}\n\n/** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */\nexport interface WebSocketTopics {\n /** The client the subscription messages are sent on. */\n readonly client: WebSocketClient<any, any>;\n /**\n * Hold a subscription to `topic`, and the client's connection, until the returned\n * function is called. The release function is safe to call more than once.\n */\n acquire(topic: string): () => void;\n /** The topics currently held, in the order they were first acquired. */\n active(): string[];\n /** Stop managing subscriptions. Only needed for managers created dynamically. */\n dispose(): void;\n}\n\n/**\n * Manage topic subscriptions that survive reconnects.\n *\n * - The first holder of a topic sends `subscribe(topic)`. Later holders share it.\n * - A tick after the last holder releases it, `unsubscribe(topic)` is sent, so StrictMode\n * and route transitions don't churn subscriptions.\n * - After every reconnect, every held topic is subscribed again on the new socket, before\n * messages queued while disconnected are sent.\n *\n * Subscriptions are only sent while the socket is open; nothing is queued for them.\n *\n * @example\n * ```ts\n * export const topics = createWebSocketTopics(live, {\n * subscribe: topic => ({ type: 'subscribe', topic }),\n * unsubscribe: topic => ({ type: 'unsubscribe', topic })\n * });\n *\n * // In a component:\n * useWebSocketTopic(topics, `prices:${symbol}`);\n * ```\n */\n// `const` + `NoInfer`: take `Out` from the client only, and keep literals such as\n// `type: 'subscribe'` from widening to `string` inside the callbacks.\nexport function createWebSocketTopics<const Out>(\n client: WebSocketClient<any, Out>,\n options: WebSocketTopicsOptions<NoInfer<Out>>\n): WebSocketTopics {\n const counts = new Map<string, number>();\n const pendingRemoval = new Map<string, Timer>();\n // Topics subscribed on `sentOn`. A new socket starts with none, whatever the old one had.\n let sentOn: WebSocket | null = null;\n let sent = new Set<string>();\n\n function isOpen() {\n return client.getSnapshot().status === 'open' && client.socket !== null;\n }\n\n function subscribe(topic: string) {\n if (!isOpen()) return; // sent on `open` instead\n if (client.socket !== sentOn) {\n sentOn = client.socket;\n sent = new Set();\n }\n if (sent.has(topic)) return;\n sent.add(topic);\n client.send(options.subscribe(topic));\n }\n\n function unsubscribe(topic: string) {\n if (!isOpen() || client.socket !== sentOn || !sent.delete(topic)) return;\n if (options.unsubscribe) client.send(options.unsubscribe(topic));\n }\n\n // `open` listeners run before the client flushes its queue.\n const off = client.on('open', () => {\n sentOn = client.socket;\n sent = new Set();\n for (const topic of counts.keys()) subscribe(topic);\n });\n\n return {\n client,\n acquire(topic) {\n const releaseConnection = client.acquire();\n clearTimeout(pendingRemoval.get(topic));\n pendingRemoval.delete(topic);\n counts.set(topic, (counts.get(topic) ?? 0) + 1);\n subscribe(topic);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const remaining = (counts.get(topic) ?? 1) - 1;\n if (remaining > 0) {\n counts.set(topic, remaining);\n } else {\n counts.delete(topic);\n pendingRemoval.set(\n topic,\n setTimeout(() => {\n pendingRemoval.delete(topic);\n if (!counts.has(topic)) unsubscribe(topic);\n }, 0)\n );\n }\n releaseConnection();\n };\n },\n active: () => [...counts.keys()],\n dispose() {\n off();\n for (const timer of pendingRemoval.values()) clearTimeout(timer);\n pendingRemoval.clear();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;AA8QA,IAAa,eAAb,cAAkC,MAAM;;CAEtC;;CAEA;CAEA,YACE,SACA,MACA,SACA;EACA,MAAM,SAAS,SAAS,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EAClF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;CACzB;AACF;;;AChRA,MAAM,OAAO;AAEb,MAAM,qBAAqB;CACzB,aAAa;CACb,UAAU;CACV,UAAU;CACV,QAAQ;CACR,QAAQ;AACV;AAMA,MAAM,cAAc;AAiBpB,SAAS,iBAA2B;CAClC,IAAI;CACJ,IAAI;CACJ,MAAM,UAAU,IAAI,SAAe,KAAK,Q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ACjB;EACA,IAAI,KAAK,IAAI,KAAK,GAAG;EACrB,KAAK,IAAI,KAAK;EACd,OAAO,KAAK,QAAQ,UAAU,KAAK,CAAC;CACtC;CAEA,SAAS,YAAY,OAAe;EAClC,IAAI,CAAC,OAAO,KAAK,OAAO,WAAW,UAAU,CAAC,KAAK,OAAO,KAAK,GAAG;EAClE,IAAI,QAAQ,aAAa,OAAO,KAAK,QAAQ,YAAY,KAAK,CAAC;CACjE;CAGA,MAAM,MAAM,OAAO,GAAG,cAAc;EAClC,SAAS,OAAO;EAChB,uBAAO,IAAI,IAAI;EACf,KAAK,MAAM,SAAS,OAAO,KAAK,GAAG,UAAU,KAAK;CACpD,CAAC;CAED,OAAO;EACL;EACA,QAAQ,OAAO;GACb,MAAM,oBAAoB,OAAO,QAAQ;GACzC,aAAa,eAAe,IAAI,KAAK,CAAC;GACtC,eAAe,OAAO,KAAK;GAC3B,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;GAC9C,UAAU,KAAK;GAEf,IAAI,WAAW;GACf,aAAa;IACX,IAAI,UAAU;IACd,WAAW;IACX,MAAM,aAAa,OAAO,IAAI,KAAK,KAAK,KAAK;IAC7C,IAAI,YAAY,GACd,OAAO,IAAI,OAAO,SAAS;SACtB;KACL,OAAO,OAAO,KAAK;KACnB,eAAe,IACb,OACA,iBAAiB;MACf,eAAe,OAAO,KAAK;MAC3B,IAAI,CAAC,OAAO,IAAI,KAAK,GAAG,YAAY,KAAK;KAC3C,GAAG,CAAC,CACN;IACF;IACA,kBAAkB;GACpB;EACF;EACA,cAAc,CAAC,GAAG,OAAO,KAAK,CAAC;EAC/B,UAAU;GACR,IAAI;GACJ,KAAK,MAAM,SAAS,eAAe,OAAO,GAAG,aAAa,KAAK;GAC/D,eAAe,MAAM;EACvB;CACF;AACF"}
package/dist/index.cjs CHANGED
@@ -219,6 +219,69 @@ function useAgentApproval(responder, method) {
219
219
  return mine.length ? mine : NO_REQUESTS;
220
220
  }, [waiting, method]);
221
221
  }
222
+ const append = (list, reply) => [...list, reply];
223
+ function nextFrame(callback) {
224
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(callback);
225
+ else setTimeout(callback, 16);
226
+ }
227
+ function useWebSocketStream(rpc, options = {}) {
228
+ const [state, setState] = (0, react.useState)(() => ({
229
+ value: options.reduce ? options.initial : NO_REQUESTS,
230
+ status: "idle",
231
+ error: void 0
232
+ }));
233
+ const latest = useLatest({
234
+ rpc,
235
+ options
236
+ });
237
+ const running = (0, react.useRef)(null);
238
+ const actions = (0, react.useMemo)(() => ({
239
+ abort: () => running.current?.abort(),
240
+ start(message, requestOptions) {
241
+ running.current?.abort();
242
+ const controller = running.current = new AbortController();
243
+ const { reduce, initial, batch } = latest.current.options;
244
+ const fold = reduce ?? append;
245
+ let value = reduce ? initial : NO_REQUESTS;
246
+ let frame = false;
247
+ const show = (status, error) => {
248
+ frame = false;
249
+ if (running.current === controller) setState({
250
+ value,
251
+ status,
252
+ error
253
+ });
254
+ };
255
+ show("streaming");
256
+ (async () => {
257
+ try {
258
+ const replies = latest.current.rpc.stream(message, {
259
+ ...requestOptions,
260
+ signal: controller.signal
261
+ });
262
+ for await (const reply of replies) {
263
+ value = fold(value, reply);
264
+ if (batch !== "frame") show("streaming");
265
+ else if (!frame) {
266
+ frame = true;
267
+ nextFrame(() => frame && show("streaming"));
268
+ }
269
+ }
270
+ show("done");
271
+ } catch (error) {
272
+ if (controller.signal.aborted) show("aborted");
273
+ else show("error", error);
274
+ }
275
+ })();
276
+ }
277
+ }), [latest]);
278
+ (0, react.useEffect)(() => actions.abort, [actions, rpc]);
279
+ useHold(rpc?.client ?? null, true);
280
+ return {
281
+ ...state,
282
+ ...actions
283
+ };
284
+ }
222
285
  //#endregion
223
286
  exports.useAgentApproval = useAgentApproval;
224
287
  exports.useWebSocket = useWebSocket;
@@ -226,6 +289,7 @@ exports.useWebSocketEvent = useWebSocketEvent;
226
289
  exports.useWebSocketLatency = useWebSocketLatency;
227
290
  exports.useWebSocketState = useWebSocketState;
228
291
  exports.useWebSocketStatus = useWebSocketStatus;
292
+ exports.useWebSocketStream = useWebSocketStream;
229
293
  exports.useWebSocketTopic = useWebSocketTopic;
230
294
  Object.keys(__core_cjs).forEach(function(k) {
231
295
  if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {