tempest-react-sdk 0.61.0 → 0.62.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/README.md +9 -7
- package/dist/sse/create-event-stream.cjs +1 -1
- package/dist/sse/create-event-stream.cjs.map +1 -1
- package/dist/sse/create-event-stream.js +32 -27
- package/dist/sse/create-event-stream.js.map +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/tempest-react-sdk.d.ts +180 -21
- package/dist/utils/dev-mode.cjs.map +1 -1
- package/dist/utils/dev-mode.js.map +1 -1
- package/dist/utils/json-frame.cjs +1 -1
- package/dist/utils/json-frame.cjs.map +1 -1
- package/dist/utils/json-frame.js +33 -14
- package/dist/utils/json-frame.js.map +1 -1
- package/dist/utils/schema-like.cjs +2 -0
- package/dist/utils/schema-like.cjs.map +1 -0
- package/dist/utils/schema-like.js +43 -0
- package/dist/utils/schema-like.js.map +1 -0
- package/dist/ws/create-web-socket.cjs +1 -1
- package/dist/ws/create-web-socket.cjs.map +1 -1
- package/dist/ws/create-web-socket.js +54 -38
- package/dist/ws/create-web-socket.js.map +1 -1
- package/dist/ws/use-web-socket.cjs +1 -1
- package/dist/ws/use-web-socket.cjs.map +1 -1
- package/dist/ws/use-web-socket.js +5 -3
- package/dist/ws/use-web-socket.js.map +1 -1
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@ import { decodeFrame as e } from "../utils/json-frame.js";
|
|
|
2
2
|
import { backoffDelay as t, isRejectionCloseCode as n, shouldRetryClose as r } from "./resilience.js";
|
|
3
3
|
//#region src/ws/create-web-socket.ts
|
|
4
4
|
function i(i, a = {}) {
|
|
5
|
-
let { protocols: ee, maxRetries: o = 10, initialBackoff: s = 1e3, maxBackoff: c = 3e4, jitter: l = .3, handshakeTimeout: u = 8e3, silenceTimeout: d = 0, waitForOnline: f = !0, pingInterval: p = 0, pingPayload: te = JSON.stringify({ type: "ping" }), respondToPing:
|
|
5
|
+
let { protocols: ee, maxRetries: o = 10, initialBackoff: s = 1e3, maxBackoff: c = 3e4, jitter: l = .3, handshakeTimeout: u = 8e3, silenceTimeout: d = 0, waitForOnline: f = !0, pingInterval: p = 0, pingPayload: te = JSON.stringify({ type: "ping" }), respondToPing: m = !0, pongPayload: h = JSON.stringify({ type: "pong" }), queueWhileClosed: ne = !1, maxQueuedMessages: re = 100, parser: ie, onOpen: ae, onMessage: oe, onClose: se, onError: g, onParseError: _, schema: v, onValidationError: y, onStatusChange: b, onReconnecting: x, onReconnected: S, onLost: C } = a, w = null, T = null, E = null, D = null, O = null, k = null, A = d, j = 0, M = "idle", N = !1, P = !1, F = [], I = null, L = null, R = new Promise((e, t) => {
|
|
6
6
|
I = e, L = t;
|
|
7
7
|
});
|
|
8
8
|
R.catch(() => void 0);
|
|
@@ -10,33 +10,41 @@ function i(i, a = {}) {
|
|
|
10
10
|
return typeof e == "object" && !!e && e.type === "ping";
|
|
11
11
|
}
|
|
12
12
|
function B(e) {
|
|
13
|
-
|
|
13
|
+
if (!e.includes("\"ping\"")) return !1;
|
|
14
|
+
try {
|
|
15
|
+
return z(JSON.parse(e));
|
|
16
|
+
} catch {
|
|
17
|
+
return !1;
|
|
18
|
+
}
|
|
14
19
|
}
|
|
15
20
|
function V(e) {
|
|
21
|
+
for (; F.length > 0 && e.readyState === WebSocket.OPEN;) e.send(F.shift());
|
|
22
|
+
}
|
|
23
|
+
function H(e) {
|
|
16
24
|
M !== e && (M = e, b?.(e));
|
|
17
25
|
}
|
|
18
|
-
function
|
|
26
|
+
function U() {
|
|
19
27
|
E &&= (clearInterval(E), null);
|
|
20
28
|
}
|
|
21
|
-
function
|
|
29
|
+
function W() {
|
|
22
30
|
D &&= (clearTimeout(D), null);
|
|
23
31
|
}
|
|
24
|
-
function
|
|
32
|
+
function G() {
|
|
25
33
|
O &&= (clearTimeout(O), null);
|
|
26
34
|
}
|
|
27
|
-
function
|
|
28
|
-
!p || p <= 0 || (
|
|
35
|
+
function ce() {
|
|
36
|
+
!p || p <= 0 || (U(), E = setInterval(() => {
|
|
29
37
|
w?.readyState === WebSocket.OPEN && w.send(te);
|
|
30
38
|
}, p));
|
|
31
39
|
}
|
|
32
40
|
function K() {
|
|
33
|
-
|
|
41
|
+
G(), !(N || A <= 0) && (O = setTimeout(le, A));
|
|
34
42
|
}
|
|
35
|
-
function
|
|
36
|
-
|
|
43
|
+
function le() {
|
|
44
|
+
G(), !N && w && (J(w), w = null, H("closed"), X());
|
|
37
45
|
}
|
|
38
|
-
function
|
|
39
|
-
|
|
46
|
+
function q(e) {
|
|
47
|
+
W(), !(N || e.readyState !== WebSocket.CONNECTING) && (J(e), w === e && (w = null), H("closed"), X());
|
|
40
48
|
}
|
|
41
49
|
function J(e) {
|
|
42
50
|
e.onopen = null, e.onmessage = null, e.onerror = null, e.onclose = null;
|
|
@@ -45,7 +53,7 @@ function i(i, a = {}) {
|
|
|
45
53
|
} catch {}
|
|
46
54
|
}
|
|
47
55
|
function Y(e) {
|
|
48
|
-
if (
|
|
56
|
+
if (G(), W(), Z(), e === "rejected" && (N = !0), H("error"), !P && L) {
|
|
49
57
|
let t = L;
|
|
50
58
|
L = null, I = null, t(/* @__PURE__ */ Error(`websocket_${e}`));
|
|
51
59
|
}
|
|
@@ -63,12 +71,12 @@ function i(i, a = {}) {
|
|
|
63
71
|
jitter: l
|
|
64
72
|
});
|
|
65
73
|
if (j += 1, x?.(j, o), f && typeof navigator < "u" && navigator.onLine === !1) {
|
|
66
|
-
|
|
74
|
+
ue();
|
|
67
75
|
return;
|
|
68
76
|
}
|
|
69
77
|
T = setTimeout(Q, e);
|
|
70
78
|
}
|
|
71
|
-
function
|
|
79
|
+
function ue() {
|
|
72
80
|
if (k || typeof window > "u") return;
|
|
73
81
|
let e = () => {
|
|
74
82
|
Z(), N || Q();
|
|
@@ -80,33 +88,41 @@ function i(i, a = {}) {
|
|
|
80
88
|
}
|
|
81
89
|
function Q() {
|
|
82
90
|
if (N) return;
|
|
83
|
-
if (T = null,
|
|
91
|
+
if (T = null, W(), w) {
|
|
84
92
|
let e = w;
|
|
85
93
|
e.onmessage = null, e.onclose = null, e.onerror = null, e.readyState !== WebSocket.CONNECTING && (e.onopen = null), $(e);
|
|
86
94
|
}
|
|
87
|
-
|
|
95
|
+
H("connecting");
|
|
88
96
|
let t = new WebSocket(i, ee);
|
|
89
|
-
w = t, u > 0 && (D = setTimeout(() =>
|
|
90
|
-
|
|
97
|
+
w = t, u > 0 && (D = setTimeout(() => q(t), u)), t.onopen = (e) => {
|
|
98
|
+
W();
|
|
91
99
|
let n = j > 0;
|
|
92
|
-
if (j = 0, P = !0,
|
|
100
|
+
if (j = 0, P = !0, H("open"), ce(), K(), V(t), I) {
|
|
93
101
|
let e = I;
|
|
94
102
|
I = null, L = null, e();
|
|
95
103
|
}
|
|
96
|
-
|
|
104
|
+
ae?.(e), n && S?.();
|
|
97
105
|
}, t.onmessage = (n) => {
|
|
98
106
|
K();
|
|
99
|
-
let r = typeof n.data == "string" ? n.data : "", i = e(r,
|
|
100
|
-
|
|
107
|
+
let r = typeof n.data == "string" ? n.data : "", i = e(r, "createWebSocket", {
|
|
108
|
+
parser: ie,
|
|
109
|
+
onParseError: _,
|
|
110
|
+
schema: v,
|
|
111
|
+
onValidationError: y
|
|
112
|
+
});
|
|
113
|
+
if (!i.delivered) {
|
|
114
|
+
m && t.readyState === WebSocket.OPEN && B(r) && t.send(h);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
101
117
|
let a = i.data;
|
|
102
|
-
|
|
118
|
+
m && z(a) && t.readyState === WebSocket.OPEN && t.send(h), oe?.({
|
|
103
119
|
data: a,
|
|
104
120
|
raw: n
|
|
105
121
|
});
|
|
106
122
|
}, t.onerror = (e) => {
|
|
107
|
-
|
|
123
|
+
g?.(e);
|
|
108
124
|
}, t.onclose = (e) => {
|
|
109
|
-
if (
|
|
125
|
+
if (W(), U(), G(), se?.(e), w = null, H("closed"), !N) {
|
|
110
126
|
if (n(e.code)) {
|
|
111
127
|
Y("rejected");
|
|
112
128
|
return;
|
|
@@ -119,15 +135,15 @@ function i(i, a = {}) {
|
|
|
119
135
|
}
|
|
120
136
|
};
|
|
121
137
|
}
|
|
122
|
-
function
|
|
123
|
-
return w?.readyState === WebSocket.OPEN ? (w.send(e), !0) : !
|
|
138
|
+
function de(e) {
|
|
139
|
+
return w?.readyState === WebSocket.OPEN ? (w.send(e), !0) : !ne || N ? !1 : (F.length >= re && F.shift(), F.push(e), !0);
|
|
124
140
|
}
|
|
125
|
-
function
|
|
126
|
-
if (N = !0, T &&= (clearTimeout(T), null),
|
|
141
|
+
function fe(e, t) {
|
|
142
|
+
if (N = !0, T &&= (clearTimeout(T), null), U(), W(), G(), Z(), j = 0, F.length = 0, L) {
|
|
127
143
|
let e = L;
|
|
128
144
|
L = null, I = null, e(/* @__PURE__ */ Error("websocket_closed"));
|
|
129
145
|
}
|
|
130
|
-
w &&= (
|
|
146
|
+
w &&= (H("closing"), $(w, e, t), null), H("closed");
|
|
131
147
|
}
|
|
132
148
|
function $(e, t, n) {
|
|
133
149
|
if (e.readyState === WebSocket.CONNECTING) {
|
|
@@ -136,17 +152,17 @@ function i(i, a = {}) {
|
|
|
136
152
|
}
|
|
137
153
|
e.close(t, n);
|
|
138
154
|
}
|
|
139
|
-
function
|
|
155
|
+
function pe() {
|
|
140
156
|
T &&= (clearTimeout(T), null), Z(), j = 0, N = !1, Q();
|
|
141
157
|
}
|
|
142
|
-
function
|
|
143
|
-
A = Number.isFinite(e) && e > 0 ? e : 0, w?.readyState === WebSocket.OPEN ? K() :
|
|
158
|
+
function me(e) {
|
|
159
|
+
A = Number.isFinite(e) && e > 0 ? e : 0, w?.readyState === WebSocket.OPEN ? K() : G();
|
|
144
160
|
}
|
|
145
161
|
return Q(), {
|
|
146
|
-
send:
|
|
147
|
-
close:
|
|
148
|
-
reconnect:
|
|
149
|
-
setSilenceTimeout:
|
|
162
|
+
send: de,
|
|
163
|
+
close: fe,
|
|
164
|
+
reconnect: pe,
|
|
165
|
+
setSilenceTimeout: me,
|
|
150
166
|
opened: R,
|
|
151
167
|
get status() {
|
|
152
168
|
return M;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-web-socket.js","names":[],"sources":["../../src/ws/create-web-socket.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — reconnect with backoff, heartbeat,\n * the handshake and silence timers that detect a link which never fails out loud,\n * the send queue that survives a disconnect and the listener set that must be re-\n * attached to each new socket — one connection's lifetime, one closure. The queue\n * and the reconnect timer are the same decision seen twice.\n */\nimport {\n backoffDelay,\n isRejectionCloseCode,\n shouldRetryClose,\n type WebSocketLostReason,\n} from \"./resilience\";\nimport { decodeFrame } from \"../utils/json-frame\";\n\nexport type WebSocketStatus = \"idle\" | \"connecting\" | \"open\" | \"closing\" | \"closed\" | \"error\";\n\nexport interface WebSocketMessage<T> {\n /** Parsed payload — JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** The original `MessageEvent`. */\n raw: MessageEvent;\n}\n\nexport interface CreateWebSocketOptions<T> {\n /** Subprotocol(s) forwarded to the `WebSocket` constructor. */\n protocols?: string | string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable. */\n maxRetries?: number;\n /** Initial backoff (ms). Doubles each attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff (ms). Default: 30000. */\n maxBackoff?: number;\n /**\n * Fraction of each backoff delay added at random, 0–1. Default: 0.3.\n *\n * Matters when the *server* is what went down: every client retries on the\n * same schedule, so the box comes back up into a synchronized stampede. Pass\n * `0` for a fixed schedule.\n */\n jitter?: number;\n /**\n * How long one handshake may stay in `CONNECTING` before the attempt is\n * abandoned and retried (ms). Default: 8000. Pass 0 to disable.\n *\n * A `WebSocket` that cannot reach its server does not necessarily fail: it\n * sits in `CONNECTING` firing neither `open` nor `close` nor `error`. A retry\n * chain built only on those events stops on its first hung attempt and never\n * moves again — and hung, rather than refused, is precisely how a bad mobile\n * link behaves, which is the case reconnection exists for.\n */\n handshakeTimeout?: number;\n /**\n * Silence tolerated on an open socket before the link is treated as dead (ms).\n * Default: 0 (off).\n *\n * The socket only reports a connection that closes cleanly. A link that dies\n * mid-flight leaves `readyState` at `OPEN` on this side with nothing ever\n * arriving again, so silence is the only symptom available. The timer is\n * re-armed by **any** inbound frame, not just by pings — traffic is traffic.\n *\n * Set it to a comfortable multiple of the server's ping interval (2.5× is a\n * good default) so one dropped ping is not mistaken for an outage. When the\n * server announces its own interval in the handshake, feed that back with\n * {@link WebSocketController.setSilenceTimeout} instead of hard-coding the\n * value on both ends.\n */\n silenceTimeout?: number;\n /**\n * Suspend the retry schedule while `navigator.onLine` is false, and resume on\n * the `online` event. Default: true.\n *\n * Burning retries against a radio that is switched off is how a phone\n * exhausts its budget inside a tunnel and gives up exactly when it comes out\n * the other side.\n */\n waitForOnline?: boolean;\n /**\n * Ping interval (ms). When set, the client sends `pingPayload` periodically\n * to keep the socket alive. Default: 0 (disabled).\n *\n * Leave it off against a `tempest-fastapi-sdk` server: that server pings on\n * its own and answers a client-sent `{\"type\":\"ping\"}` with nothing, while a\n * strict handler rejects the unknown frame. What it needs from the client\n * is the `pong` reply, which `respondToPing` sends for you.\n */\n pingInterval?: number;\n /** Payload sent on each ping. Default: `JSON.stringify({ type: \"ping\" })`. */\n pingPayload?: string | Blob | BufferSource;\n /**\n * Reply to a server `{\"type\":\"ping\"}` with `pongPayload`. Default: true.\n *\n * `tempest-fastapi-sdk` closes a socket with code `4408` when no `pong`\n * arrives within `WS_HEARTBEAT_TIMEOUT_SECONDS`, so a client that stays\n * silent is dropped once per timeout. The ping is still forwarded to\n * `onMessage` — the reply is sent before your handler runs.\n */\n respondToPing?: boolean;\n /** Payload sent in reply to a server ping. Default: `JSON.stringify({ type: \"pong\" })`. */\n pongPayload?: string | Blob | BufferSource;\n /**\n * Buffer payloads sent while the socket is not open and flush them on the\n * next `open`. Default: false — `send()` returns false and drops.\n *\n * Without it, an action fired during reconnect backoff vanishes and the UI\n * cannot tell \"never sent\" from \"sent and ignored\".\n */\n queueWhileClosed?: boolean;\n /** Cap on buffered payloads when `queueWhileClosed` is on. Default: 100. */\n maxQueuedMessages?: number;\n /** Parse incoming frames. Default: JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n onOpen?: (event: Event) => void;\n onMessage?: (message: WebSocketMessage<T>) => void;\n onClose?: (event: CloseEvent) => void;\n onError?: (event: Event) => void;\n onStatusChange?: (status: WebSocketStatus) => void;\n /**\n * A retry has been scheduled. `attempt` is 1-based, `total` is `maxRetries`.\n *\n * Reconnecting is not an error and reads badly as one: announcing every\n * attempt puts a fresh \"the connection dropped\" in front of someone whose\n * session is in the middle of coming back on its own. Show a quiet\n * reconnecting state here and treat {@link CreateWebSocketOptions.onLost} as\n * the failure.\n */\n onReconnecting?: (attempt: number, total: number) => void;\n /**\n * The socket is back up after at least one retry.\n *\n * Nothing is resumed for you: a server that keys state by connection sees a\n * brand-new client, so this is where the caller re-subscribes, re-joins or\n * refetches whatever the gap invalidated.\n */\n onReconnected?: () => void;\n /**\n * No further attempt will be made — `\"rejected\"` when the server refused the\n * client outright (close code 4400–4499, minus the 4408 heartbeat timeout),\n * `\"exhausted\"` when the schedule ran out.\n *\n * This is the one that deserves UI, because it is the only state the caller\n * can act on: offer a \"try again\" that calls\n * {@link WebSocketController.reconnect}.\n */\n onLost?: (reason: WebSocketLostReason) => void;\n}\n\nexport interface WebSocketController {\n /** Send a payload over the current connection. No-op when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Close the connection and stop reconnecting. */\n close: (code?: number, reason?: string) => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For the common case where the server announces its heartbeat interval in\n * the first frame, so the tolerated silence is not hard-coded on both ends:\n *\n * ```ts\n * onMessage: ({ data }) => {\n * if (data.type === \"welcome\") socket.setSilenceTimeout(data.heartbeat_seconds * 2500);\n * }\n * ```\n */\n setSilenceTimeout: (ms: number) => void;\n /**\n * Resolves on the first successful open, rejects when the socket is lost\n * before ever opening.\n *\n * Joining and dropping are different events: a call that never connected has\n * to be reported, while one that dropped mid-session should reconnect\n * quietly. Await this for the join, handle\n * {@link CreateWebSocketOptions.onLost} for the drop. Pair it with\n * `maxRetries: 0` when the first attempt should fail fast instead of\n * spending the whole schedule on a server that is not there.\n */\n opened: Promise<void>;\n /** Current connection status. */\n readonly status: WebSocketStatus;\n}\n\n/**\n * Open a WebSocket that survives a bad network: exponential backoff with jitter,\n * a handshake timeout, a silence watchdog, optional heartbeat pings and typed\n * JSON parsing.\n *\n * Three failure modes are covered that an event-driven retry loop misses on its\n * own, because none of them fire an event: a handshake that hangs instead of\n * failing, an open socket whose link died mid-flight, and a device with its\n * radio off burning the retry budget. See `handshakeTimeout`, `silenceTimeout`\n * and `waitForOnline`.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Controller exposing `send`, `close`, `reconnect`, `setSilenceTimeout`,\n * `opened` and `status`.\n *\n * @example\n * const socket = createWebSocket(url, {\n * silenceTimeout: 75_000,\n * onReconnecting: (n, total) => setBanner(`Reconectando ${n}/${total}…`),\n * onReconnected: () => refetchEverything(),\n * onLost: (reason) => setBanner(reason === \"rejected\" ? \"Acesso negado\" : \"Sem conexão\"),\n * });\n * await socket.opened;\n */\nexport function createWebSocket<T = unknown>(\n url: string,\n options: CreateWebSocketOptions<T> = {},\n): WebSocketController {\n const {\n protocols,\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n jitter = 0.3,\n handshakeTimeout = 8000,\n silenceTimeout = 0,\n waitForOnline = true,\n pingInterval = 0,\n pingPayload = JSON.stringify({ type: \"ping\" }),\n respondToPing = true,\n pongPayload = JSON.stringify({ type: \"pong\" }),\n queueWhileClosed = false,\n maxQueuedMessages = 100,\n parser,\n onOpen,\n onMessage,\n onClose,\n onError,\n onParseError,\n onStatusChange,\n onReconnecting,\n onReconnected,\n onLost,\n } = options;\n\n let socket: WebSocket | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let silenceTimer: ReturnType<typeof setTimeout> | null = null;\n let onlineListener: (() => void) | null = null;\n let silenceWindow = silenceTimeout;\n let retries = 0;\n let status: WebSocketStatus = \"idle\";\n let closed = false;\n let everOpened = false;\n const outbox: Array<string | Blob | BufferSource> = [];\n\n let settleOpen: (() => void) | null = null;\n let failOpen: ((error: Error) => void) | null = null;\n const opened = new Promise<void>((resolve, reject) => {\n settleOpen = resolve;\n failOpen = reject;\n });\n opened.catch(() => undefined);\n\n /** True for a decoded frame that is the server's heartbeat ping. */\n function isServerPing(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { type?: unknown }).type === \"ping\"\n );\n }\n\n /** Send everything buffered while the socket was down, oldest first. */\n function flushOutbox(ws: WebSocket): void {\n while (outbox.length > 0 && ws.readyState === WebSocket.OPEN) {\n ws.send(outbox.shift()!);\n }\n }\n\n function setStatus(next: WebSocketStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function clearPing(): void {\n if (pingTimer) {\n clearInterval(pingTimer);\n pingTimer = null;\n }\n }\n\n function clearHandshake(): void {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n }\n\n function clearSilence(): void {\n if (silenceTimer) {\n clearTimeout(silenceTimer);\n silenceTimer = null;\n }\n }\n\n function startPing(): void {\n if (!pingInterval || pingInterval <= 0) return;\n clearPing();\n pingTimer = setInterval(() => {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(pingPayload);\n }\n }, pingInterval);\n }\n\n /**\n * Restart the silence timer, because something just arrived.\n *\n * Armed off any inbound frame rather than off pongs alone: a busy exchange\n * already proves the link is carrying data, and a protocol whose pings the\n * client never sees would otherwise reconnect in the middle of working\n * traffic.\n */\n function armSilence(): void {\n clearSilence();\n if (closed || silenceWindow <= 0) return;\n silenceTimer = setTimeout(onSilence, silenceWindow);\n }\n\n /**\n * Treat a socket that went quiet as dead and start reconnecting.\n *\n * Handlers are detached before closing so the synthetic `close` does not also\n * schedule a retry — that would advance the backoff twice for one failure and\n * halve the time the connection is given to recover.\n */\n function onSilence(): void {\n clearSilence();\n if (closed || !socket) return;\n detach(socket);\n socket = null;\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n /**\n * Abandon a handshake that never resolved either way.\n *\n * The socket is closed while still `CONNECTING`, which is the one case the\n * console warns about — and the right trade here, because the alternative is\n * deferring the close to an `open` event that by definition is not coming.\n */\n function abandonHandshake(ws: WebSocket): void {\n clearHandshake();\n if (closed || ws.readyState !== WebSocket.CONNECTING) return;\n detach(ws);\n if (socket === ws) socket = null;\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n /** Drop every handler and close, so the socket can die without being heard. */\n function detach(ws: WebSocket): void {\n ws.onopen = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n try {\n ws.close();\n } catch {\n /* already unusable — nothing to release and nothing to report */\n }\n }\n\n /** Stop for good, telling the caller which of the two dead ends it is. */\n function lose(reason: WebSocketLostReason): void {\n clearSilence();\n clearHandshake();\n clearNetworkWait();\n if (reason === \"rejected\") closed = true;\n setStatus(\"error\");\n if (!everOpened && failOpen) {\n const reject = failOpen;\n failOpen = null;\n settleOpen = null;\n reject(new Error(`websocket_${reason}`));\n }\n onLost?.(reason);\n }\n\n /**\n * Queue the next attempt, or wait for the network when there is none.\n *\n * While the browser reports no connectivity the schedule is suspended and the\n * `online` event drives the next attempt instead, so a device in a tunnel\n * does not spend its whole budget before coming out the other side.\n */\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n lose(\"exhausted\");\n return;\n }\n const delay = backoffDelay(retries, { initialBackoff, maxBackoff, jitter });\n retries += 1;\n onReconnecting?.(retries, maxRetries);\n\n if (waitForOnline && typeof navigator !== \"undefined\" && navigator.onLine === false) {\n waitForNetwork();\n return;\n }\n retryTimer = setTimeout(connect, delay);\n }\n\n function waitForNetwork(): void {\n if (onlineListener || typeof window === \"undefined\") return;\n const listener = (): void => {\n clearNetworkWait();\n if (!closed) connect();\n };\n onlineListener = listener;\n window.addEventListener(\"online\", listener);\n }\n\n function clearNetworkWait(): void {\n if (!onlineListener || typeof window === \"undefined\") return;\n window.removeEventListener(\"online\", onlineListener);\n onlineListener = null;\n }\n\n /**\n * Open a socket, replacing whatever is there.\n *\n * The handshake timer is cleared first because it belongs to the socket\n * being replaced, and it holds a reference to it: left armed, it fires later\n * against a connection nobody is waiting for, clears the *new* socket's\n * timer on its way through, and schedules a retry that drops a connection\n * still in flight. `reconnect()` on a hung socket is the path that reaches\n * it.\n */\n function connect(): void {\n if (closed) return;\n retryTimer = null;\n clearHandshake();\n if (socket) {\n const previous = socket;\n previous.onmessage = null;\n previous.onclose = null;\n previous.onerror = null;\n if (previous.readyState !== WebSocket.CONNECTING) previous.onopen = null;\n closeSocket(previous);\n }\n setStatus(\"connecting\");\n\n const ws = new WebSocket(url, protocols);\n socket = ws;\n\n if (handshakeTimeout > 0) {\n handshakeTimer = setTimeout(() => abandonHandshake(ws), handshakeTimeout);\n }\n\n ws.onopen = (event) => {\n clearHandshake();\n const recovered = retries > 0;\n retries = 0;\n everOpened = true;\n setStatus(\"open\");\n startPing();\n armSilence();\n flushOutbox(ws);\n if (settleOpen) {\n const resolve = settleOpen;\n settleOpen = null;\n failOpen = null;\n resolve();\n }\n onOpen?.(event);\n if (recovered) onReconnected?.();\n };\n\n ws.onmessage = (event) => {\n armSilence();\n const raw = typeof event.data === \"string\" ? event.data : \"\";\n const decoded = decodeFrame<T>(raw, parser, onParseError, \"createWebSocket\");\n if (!decoded.delivered) return;\n const data = decoded.data;\n if (respondToPing && isServerPing(data) && ws.readyState === WebSocket.OPEN) {\n ws.send(pongPayload);\n }\n onMessage?.({ data, raw: event });\n };\n\n ws.onerror = (event) => {\n onError?.(event);\n };\n\n /**\n * Classify the close before deciding anything.\n *\n * Three outcomes, in order: a refusal never gets better by trying again;\n * a died-in-flight or temporarily-unavailable close is retried; an\n * ordinary goodbye (a clean 1000) is the session ending on purpose and\n * deserves no error. The one exception is a goodbye on a socket that\n * never opened — the server hung up during the handshake, which the\n * caller awaiting `opened` has to hear about.\n */\n ws.onclose = (event) => {\n clearHandshake();\n clearPing();\n clearSilence();\n onClose?.(event);\n socket = null;\n setStatus(\"closed\");\n if (closed) return;\n if (isRejectionCloseCode(event.code)) {\n lose(\"rejected\");\n return;\n }\n if (shouldRetryClose(event.code, event.wasClean)) {\n scheduleReconnect();\n return;\n }\n if (!everOpened) lose(\"rejected\");\n };\n }\n\n function send(payload: string | Blob | BufferSource): boolean {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(payload);\n return true;\n }\n if (!queueWhileClosed || closed) return false;\n if (outbox.length >= maxQueuedMessages) outbox.shift();\n outbox.push(payload);\n return true;\n }\n\n function close(code?: number, reason?: string): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearPing();\n clearHandshake();\n clearSilence();\n clearNetworkWait();\n retries = 0;\n outbox.length = 0;\n if (failOpen) {\n const reject = failOpen;\n failOpen = null;\n settleOpen = null;\n reject(new Error(\"websocket_closed\"));\n }\n if (socket) {\n setStatus(\"closing\");\n closeSocket(socket, code, reason);\n socket = null;\n }\n setStatus(\"closed\");\n }\n\n /**\n * Close a socket without the \"closed before the connection is established\"\n * console warning.\n *\n * A socket still in `CONNECTING` cannot be closed cleanly — the browser\n * logs that warning on every attempt. React's StrictMode mounts, unmounts\n * and remounts each component in development, so the first socket is\n * always torn down mid-handshake and the message shows up in every dev\n * session of every app using the hook. Deferring the close to `onopen`\n * costs one round trip and keeps the console usable.\n */\n function closeSocket(ws: WebSocket, code?: number, reason?: string): void {\n if (ws.readyState === WebSocket.CONNECTING) {\n ws.onopen = () => ws.close(code, reason);\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n return;\n }\n ws.close(code, reason);\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearNetworkWait();\n retries = 0;\n closed = false;\n connect();\n }\n\n function setSilenceTimeout(ms: number): void {\n silenceWindow = Number.isFinite(ms) && ms > 0 ? ms : 0;\n if (socket?.readyState === WebSocket.OPEN) armSilence();\n else clearSilence();\n }\n\n connect();\n\n return {\n send,\n close,\n reconnect,\n setSilenceTimeout,\n opened,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":";;;AA0NA,SAAgB,EACZ,GACA,IAAqC,CAAC,GACnB;CACnB,IAAM,EACF,eACA,gBAAa,IACb,oBAAiB,KACjB,gBAAa,KACb,YAAS,IACT,sBAAmB,KACnB,oBAAiB,GACjB,mBAAgB,IAChB,kBAAe,GACf,kBAAc,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC,GAC7C,oBAAgB,IAChB,kBAAc,KAAK,UAAU,EAAE,MAAM,OAAO,CAAC,GAC7C,sBAAmB,IACnB,uBAAoB,KACpB,WACA,WACA,cACA,YACA,aACA,kBACA,mBACA,mBACA,kBACA,cACA,GAEA,IAA2B,MAC3B,IAAmD,MACnD,IAAmD,MACnD,IAAuD,MACvD,IAAqD,MACrD,IAAsC,MACtC,IAAgB,GAChB,IAAU,GACV,IAA0B,QAC1B,IAAS,IACT,IAAa,IACX,IAA8C,CAAC,GAEjD,IAAkC,MAClC,IAA4C,MAC1C,IAAS,IAAI,SAAe,GAAS,MAAW;EAElD,AADA,IAAa,GACb,IAAW;CACf,CA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,EAAO,gBAAI,MAAM,kBAAkB,CAAC;EACxC;EAMA,AALA,AAGI,OAFA,EAAU,SAAS,GACnB,EAAY,GAAQ,GAAM,CAAM,GACvB,OAEb,EAAU,QAAQ;CACtB;CAaA,SAAS,EAAY,GAAe,GAAe,GAAuB;EACtE,IAAI,EAAG,eAAe,UAAU,YAAY;GAIxC,AAHA,EAAG,eAAe,EAAG,MAAM,GAAM,CAAM,GACvC,EAAG,YAAY,MACf,EAAG,UAAU,MACb,EAAG,UAAU;GACb;EACJ;EACA,EAAG,MAAM,GAAM,CAAM;CACzB;CAEA,SAAS,KAAkB;EAQvB,AAPA,AAEI,OADA,aAAa,CAAU,GACV,OAEjB,EAAiB,GACjB,IAAU,GACV,IAAS,IACT,EAAQ;CACZ;CAEA,SAAS,GAAkB,GAAkB;EAEzC,AADA,IAAgB,OAAO,SAAS,CAAE,KAAK,IAAK,IAAI,IAAK,GACjD,GAAQ,eAAe,UAAU,OAAM,EAAW,IACjD,EAAa;CACtB;CAIA,OAFA,EAAQ,GAED;EACH;EACA;EACA;EACA;EACA;EACA,IAAI,SAAS;GACT,OAAO;EACX;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"create-web-socket.js","names":[],"sources":["../../src/ws/create-web-socket.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — reconnect with backoff, heartbeat,\n * the handshake and silence timers that detect a link which never fails out loud,\n * the send queue that survives a disconnect and the listener set that must be re-\n * attached to each new socket — one connection's lifetime, one closure. The queue\n * and the reconnect timer are the same decision seen twice.\n */\nimport {\n backoffDelay,\n isRejectionCloseCode,\n shouldRetryClose,\n type WebSocketLostReason,\n} from \"./resilience\";\nimport { decodeFrame } from \"../utils/json-frame\";\nimport type { SchemaIssue, SchemaLike } from \"../utils/schema-like\";\n\nexport type WebSocketStatus = \"idle\" | \"connecting\" | \"open\" | \"closing\" | \"closed\" | \"error\";\n\nexport interface WebSocketMessage<T> {\n /** Parsed payload — validated when `schema` is set, JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** The original `MessageEvent`. */\n raw: MessageEvent;\n}\n\nexport interface CreateWebSocketOptions<T> {\n /** Subprotocol(s) forwarded to the `WebSocket` constructor. */\n protocols?: string | string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable. */\n maxRetries?: number;\n /** Initial backoff (ms). Doubles each attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff (ms). Default: 30000. */\n maxBackoff?: number;\n /**\n * Fraction of each backoff delay added at random, 0–1. Default: 0.3.\n *\n * Matters when the *server* is what went down: every client retries on the\n * same schedule, so the box comes back up into a synchronized stampede. Pass\n * `0` for a fixed schedule.\n */\n jitter?: number;\n /**\n * How long one handshake may stay in `CONNECTING` before the attempt is\n * abandoned and retried (ms). Default: 8000. Pass 0 to disable.\n *\n * A `WebSocket` that cannot reach its server does not necessarily fail: it\n * sits in `CONNECTING` firing neither `open` nor `close` nor `error`. A retry\n * chain built only on those events stops on its first hung attempt and never\n * moves again — and hung, rather than refused, is precisely how a bad mobile\n * link behaves, which is the case reconnection exists for.\n */\n handshakeTimeout?: number;\n /**\n * Silence tolerated on an open socket before the link is treated as dead (ms).\n * Default: 0 (off).\n *\n * The socket only reports a connection that closes cleanly. A link that dies\n * mid-flight leaves `readyState` at `OPEN` on this side with nothing ever\n * arriving again, so silence is the only symptom available. The timer is\n * re-armed by **any** inbound frame, not just by pings — traffic is traffic.\n *\n * Set it to a comfortable multiple of the server's ping interval (2.5× is a\n * good default) so one dropped ping is not mistaken for an outage. When the\n * server announces its own interval in the handshake, feed that back with\n * {@link WebSocketController.setSilenceTimeout} instead of hard-coding the\n * value on both ends.\n */\n silenceTimeout?: number;\n /**\n * Suspend the retry schedule while `navigator.onLine` is false, and resume on\n * the `online` event. Default: true.\n *\n * Burning retries against a radio that is switched off is how a phone\n * exhausts its budget inside a tunnel and gives up exactly when it comes out\n * the other side.\n */\n waitForOnline?: boolean;\n /**\n * Ping interval (ms). When set, the client sends `pingPayload` periodically\n * to keep the socket alive. Default: 0 (disabled).\n *\n * Leave it off against a `tempest-fastapi-sdk` server: that server pings on\n * its own and answers a client-sent `{\"type\":\"ping\"}` with nothing, while a\n * strict handler rejects the unknown frame. What it needs from the client\n * is the `pong` reply, which `respondToPing` sends for you.\n */\n pingInterval?: number;\n /** Payload sent on each ping. Default: `JSON.stringify({ type: \"ping\" })`. */\n pingPayload?: string | Blob | BufferSource;\n /**\n * Reply to a server `{\"type\":\"ping\"}` with `pongPayload`. Default: true.\n *\n * `tempest-fastapi-sdk` closes a socket with code `4408` when no `pong`\n * arrives within `WS_HEARTBEAT_TIMEOUT_SECONDS`, so a client that stays\n * silent is dropped once per timeout. The ping is still forwarded to\n * `onMessage` — the reply is sent before your handler runs.\n */\n respondToPing?: boolean;\n /** Payload sent in reply to a server ping. Default: `JSON.stringify({ type: \"pong\" })`. */\n pongPayload?: string | Blob | BufferSource;\n /**\n * Buffer payloads sent while the socket is not open and flush them on the\n * next `open`. Default: false — `send()` returns false and drops.\n *\n * Without it, an action fired during reconnect backoff vanishes and the UI\n * cannot tell \"never sent\" from \"sent and ignored\".\n */\n queueWhileClosed?: boolean;\n /** Cap on buffered payloads when `queueWhileClosed` is on. Default: 100. */\n maxQueuedMessages?: number;\n /** Parse incoming frames. Default: JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n /**\n * Schema every decoded frame must satisfy, from zod, valibot, arktype or\n * anything else exposing `~standard` or `.safeParse`.\n *\n * Without it nothing changes: the payload reaches `onMessage` announced as\n * `T` on the strength of the type argument alone, which is a promise about\n * the server that TypeScript cannot keep. With it, a frame that does not\n * match is **not** delivered — the same rule `onParseError` already follows —\n * and `onValidationError` hears why. The value delivered is the schema's\n * output, so coercions and defaults are honoured.\n *\n * When `parser` is also supplied, it decodes first and the schema validates\n * what it returned.\n *\n * A server ping is still answered when the schema drops it: the heartbeat is\n * the transport's contract with the server, not the app's with its payload,\n * and a socket that stops sending `pong` is closed with `4408` once per\n * timeout. The validation itself must be synchronous — a frame is decoded\n * inside the `message` handler and delivered from it, so an async schema\n * would deliver frames in whatever order their validations settled; that\n * case is reported through `onValidationError` instead of awaited.\n */\n schema?: SchemaLike<T>;\n /**\n * A frame was decoded but the `schema` refused it, so it was dropped.\n *\n * The one signal that does not depend on how the app's bundler resolves\n * `process`: the one-time development warning behind `onParseError` needs\n * `isDevBuild()` to be able to answer, and this callback is the app's own.\n */\n onValidationError?: (issues: SchemaIssue[], raw: string) => void;\n onOpen?: (event: Event) => void;\n onMessage?: (message: WebSocketMessage<T>) => void;\n onClose?: (event: CloseEvent) => void;\n onError?: (event: Event) => void;\n onStatusChange?: (status: WebSocketStatus) => void;\n /**\n * A retry has been scheduled. `attempt` is 1-based, `total` is `maxRetries`.\n *\n * Reconnecting is not an error and reads badly as one: announcing every\n * attempt puts a fresh \"the connection dropped\" in front of someone whose\n * session is in the middle of coming back on its own. Show a quiet\n * reconnecting state here and treat {@link CreateWebSocketOptions.onLost} as\n * the failure.\n */\n onReconnecting?: (attempt: number, total: number) => void;\n /**\n * The socket is back up after at least one retry.\n *\n * Nothing is resumed for you: a server that keys state by connection sees a\n * brand-new client, so this is where the caller re-subscribes, re-joins or\n * refetches whatever the gap invalidated.\n */\n onReconnected?: () => void;\n /**\n * No further attempt will be made — `\"rejected\"` when the server refused the\n * client outright (close code 4400–4499, minus the 4408 heartbeat timeout),\n * `\"exhausted\"` when the schedule ran out.\n *\n * This is the one that deserves UI, because it is the only state the caller\n * can act on: offer a \"try again\" that calls\n * {@link WebSocketController.reconnect}.\n */\n onLost?: (reason: WebSocketLostReason) => void;\n}\n\nexport interface WebSocketController {\n /** Send a payload over the current connection. No-op when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Close the connection and stop reconnecting. */\n close: (code?: number, reason?: string) => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For the common case where the server announces its heartbeat interval in\n * the first frame, so the tolerated silence is not hard-coded on both ends:\n *\n * ```ts\n * onMessage: ({ data }) => {\n * if (data.type === \"welcome\") socket.setSilenceTimeout(data.heartbeat_seconds * 2500);\n * }\n * ```\n */\n setSilenceTimeout: (ms: number) => void;\n /**\n * Resolves on the first successful open, rejects when the socket is lost\n * before ever opening.\n *\n * Joining and dropping are different events: a call that never connected has\n * to be reported, while one that dropped mid-session should reconnect\n * quietly. Await this for the join, handle\n * {@link CreateWebSocketOptions.onLost} for the drop. Pair it with\n * `maxRetries: 0` when the first attempt should fail fast instead of\n * spending the whole schedule on a server that is not there.\n */\n opened: Promise<void>;\n /** Current connection status. */\n readonly status: WebSocketStatus;\n}\n\n/**\n * Open a WebSocket that survives a bad network: exponential backoff with jitter,\n * a handshake timeout, a silence watchdog, optional heartbeat pings and typed\n * JSON parsing.\n *\n * Three failure modes are covered that an event-driven retry loop misses on its\n * own, because none of them fire an event: a handshake that hangs instead of\n * failing, an open socket whose link died mid-flight, and a device with its\n * radio off burning the retry budget. See `handshakeTimeout`, `silenceTimeout`\n * and `waitForOnline`.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Controller exposing `send`, `close`, `reconnect`, `setSilenceTimeout`,\n * `opened` and `status`.\n *\n * @example\n * const socket = createWebSocket(url, {\n * silenceTimeout: 75_000,\n * onReconnecting: (n, total) => setBanner(`Reconectando ${n}/${total}…`),\n * onReconnected: () => refetchEverything(),\n * onLost: (reason) => setBanner(reason === \"rejected\" ? \"Acesso negado\" : \"Sem conexão\"),\n * });\n * await socket.opened;\n */\nexport function createWebSocket<T = unknown>(\n url: string,\n options: CreateWebSocketOptions<T> = {},\n): WebSocketController {\n const {\n protocols,\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n jitter = 0.3,\n handshakeTimeout = 8000,\n silenceTimeout = 0,\n waitForOnline = true,\n pingInterval = 0,\n pingPayload = JSON.stringify({ type: \"ping\" }),\n respondToPing = true,\n pongPayload = JSON.stringify({ type: \"pong\" }),\n queueWhileClosed = false,\n maxQueuedMessages = 100,\n parser,\n onOpen,\n onMessage,\n onClose,\n onError,\n onParseError,\n schema,\n onValidationError,\n onStatusChange,\n onReconnecting,\n onReconnected,\n onLost,\n } = options;\n\n let socket: WebSocket | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n let handshakeTimer: ReturnType<typeof setTimeout> | null = null;\n let silenceTimer: ReturnType<typeof setTimeout> | null = null;\n let onlineListener: (() => void) | null = null;\n let silenceWindow = silenceTimeout;\n let retries = 0;\n let status: WebSocketStatus = \"idle\";\n let closed = false;\n let everOpened = false;\n const outbox: Array<string | Blob | BufferSource> = [];\n\n let settleOpen: (() => void) | null = null;\n let failOpen: ((error: Error) => void) | null = null;\n const opened = new Promise<void>((resolve, reject) => {\n settleOpen = resolve;\n failOpen = reject;\n });\n opened.catch(() => undefined);\n\n /** True for a decoded frame that is the server's heartbeat ping. */\n function isServerPing(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { type?: unknown }).type === \"ping\"\n );\n }\n\n /**\n * Whether an undelivered frame was a server ping, read from its raw text.\n *\n * The delivered path tests the decoded payload, which is what `parser` was\n * given the frame to produce. A frame `schema` refused never reaches that\n * path, and a heartbeat the app's schema does not describe is the normal\n * case rather than an exotic one — so the reply is decided from the wire\n * text instead, since the server closes with `4408` when no `pong` arrives.\n *\n * The substring test in front keeps the ordinary frame at one scan: only a\n * frame that mentions `\"ping\"` at all is worth parsing a second time.\n *\n * @param raw - The frame body as text.\n * @returns Whether a `pong` is owed.\n */\n function isServerPingFrame(raw: string): boolean {\n if (!raw.includes('\"ping\"')) return false;\n try {\n return isServerPing(JSON.parse(raw));\n } catch {\n return false;\n }\n }\n\n /** Send everything buffered while the socket was down, oldest first. */\n function flushOutbox(ws: WebSocket): void {\n while (outbox.length > 0 && ws.readyState === WebSocket.OPEN) {\n ws.send(outbox.shift()!);\n }\n }\n\n function setStatus(next: WebSocketStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function clearPing(): void {\n if (pingTimer) {\n clearInterval(pingTimer);\n pingTimer = null;\n }\n }\n\n function clearHandshake(): void {\n if (handshakeTimer) {\n clearTimeout(handshakeTimer);\n handshakeTimer = null;\n }\n }\n\n function clearSilence(): void {\n if (silenceTimer) {\n clearTimeout(silenceTimer);\n silenceTimer = null;\n }\n }\n\n function startPing(): void {\n if (!pingInterval || pingInterval <= 0) return;\n clearPing();\n pingTimer = setInterval(() => {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(pingPayload);\n }\n }, pingInterval);\n }\n\n /**\n * Restart the silence timer, because something just arrived.\n *\n * Armed off any inbound frame rather than off pongs alone: a busy exchange\n * already proves the link is carrying data, and a protocol whose pings the\n * client never sees would otherwise reconnect in the middle of working\n * traffic.\n */\n function armSilence(): void {\n clearSilence();\n if (closed || silenceWindow <= 0) return;\n silenceTimer = setTimeout(onSilence, silenceWindow);\n }\n\n /**\n * Treat a socket that went quiet as dead and start reconnecting.\n *\n * Handlers are detached before closing so the synthetic `close` does not also\n * schedule a retry — that would advance the backoff twice for one failure and\n * halve the time the connection is given to recover.\n */\n function onSilence(): void {\n clearSilence();\n if (closed || !socket) return;\n detach(socket);\n socket = null;\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n /**\n * Abandon a handshake that never resolved either way.\n *\n * The socket is closed while still `CONNECTING`, which is the one case the\n * console warns about — and the right trade here, because the alternative is\n * deferring the close to an `open` event that by definition is not coming.\n */\n function abandonHandshake(ws: WebSocket): void {\n clearHandshake();\n if (closed || ws.readyState !== WebSocket.CONNECTING) return;\n detach(ws);\n if (socket === ws) socket = null;\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n /** Drop every handler and close, so the socket can die without being heard. */\n function detach(ws: WebSocket): void {\n ws.onopen = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n try {\n ws.close();\n } catch {\n /* already unusable — nothing to release and nothing to report */\n }\n }\n\n /** Stop for good, telling the caller which of the two dead ends it is. */\n function lose(reason: WebSocketLostReason): void {\n clearSilence();\n clearHandshake();\n clearNetworkWait();\n if (reason === \"rejected\") closed = true;\n setStatus(\"error\");\n if (!everOpened && failOpen) {\n const reject = failOpen;\n failOpen = null;\n settleOpen = null;\n reject(new Error(`websocket_${reason}`));\n }\n onLost?.(reason);\n }\n\n /**\n * Queue the next attempt, or wait for the network when there is none.\n *\n * While the browser reports no connectivity the schedule is suspended and the\n * `online` event drives the next attempt instead, so a device in a tunnel\n * does not spend its whole budget before coming out the other side.\n */\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n lose(\"exhausted\");\n return;\n }\n const delay = backoffDelay(retries, { initialBackoff, maxBackoff, jitter });\n retries += 1;\n onReconnecting?.(retries, maxRetries);\n\n if (waitForOnline && typeof navigator !== \"undefined\" && navigator.onLine === false) {\n waitForNetwork();\n return;\n }\n retryTimer = setTimeout(connect, delay);\n }\n\n function waitForNetwork(): void {\n if (onlineListener || typeof window === \"undefined\") return;\n const listener = (): void => {\n clearNetworkWait();\n if (!closed) connect();\n };\n onlineListener = listener;\n window.addEventListener(\"online\", listener);\n }\n\n function clearNetworkWait(): void {\n if (!onlineListener || typeof window === \"undefined\") return;\n window.removeEventListener(\"online\", onlineListener);\n onlineListener = null;\n }\n\n /**\n * Open a socket, replacing whatever is there.\n *\n * The handshake timer is cleared first because it belongs to the socket\n * being replaced, and it holds a reference to it: left armed, it fires later\n * against a connection nobody is waiting for, clears the *new* socket's\n * timer on its way through, and schedules a retry that drops a connection\n * still in flight. `reconnect()` on a hung socket is the path that reaches\n * it.\n */\n function connect(): void {\n if (closed) return;\n retryTimer = null;\n clearHandshake();\n if (socket) {\n const previous = socket;\n previous.onmessage = null;\n previous.onclose = null;\n previous.onerror = null;\n if (previous.readyState !== WebSocket.CONNECTING) previous.onopen = null;\n closeSocket(previous);\n }\n setStatus(\"connecting\");\n\n const ws = new WebSocket(url, protocols);\n socket = ws;\n\n if (handshakeTimeout > 0) {\n handshakeTimer = setTimeout(() => abandonHandshake(ws), handshakeTimeout);\n }\n\n ws.onopen = (event) => {\n clearHandshake();\n const recovered = retries > 0;\n retries = 0;\n everOpened = true;\n setStatus(\"open\");\n startPing();\n armSilence();\n flushOutbox(ws);\n if (settleOpen) {\n const resolve = settleOpen;\n settleOpen = null;\n failOpen = null;\n resolve();\n }\n onOpen?.(event);\n if (recovered) onReconnected?.();\n };\n\n ws.onmessage = (event) => {\n armSilence();\n const raw = typeof event.data === \"string\" ? event.data : \"\";\n const decoded = decodeFrame<T>(raw, \"createWebSocket\", {\n parser,\n onParseError,\n schema,\n onValidationError,\n });\n if (!decoded.delivered) {\n if (respondToPing && ws.readyState === WebSocket.OPEN && isServerPingFrame(raw)) {\n ws.send(pongPayload);\n }\n return;\n }\n const data = decoded.data;\n if (respondToPing && isServerPing(data) && ws.readyState === WebSocket.OPEN) {\n ws.send(pongPayload);\n }\n onMessage?.({ data, raw: event });\n };\n\n ws.onerror = (event) => {\n onError?.(event);\n };\n\n /**\n * Classify the close before deciding anything.\n *\n * Three outcomes, in order: a refusal never gets better by trying again;\n * a died-in-flight or temporarily-unavailable close is retried; an\n * ordinary goodbye (a clean 1000) is the session ending on purpose and\n * deserves no error. The one exception is a goodbye on a socket that\n * never opened — the server hung up during the handshake, which the\n * caller awaiting `opened` has to hear about.\n */\n ws.onclose = (event) => {\n clearHandshake();\n clearPing();\n clearSilence();\n onClose?.(event);\n socket = null;\n setStatus(\"closed\");\n if (closed) return;\n if (isRejectionCloseCode(event.code)) {\n lose(\"rejected\");\n return;\n }\n if (shouldRetryClose(event.code, event.wasClean)) {\n scheduleReconnect();\n return;\n }\n if (!everOpened) lose(\"rejected\");\n };\n }\n\n function send(payload: string | Blob | BufferSource): boolean {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(payload);\n return true;\n }\n if (!queueWhileClosed || closed) return false;\n if (outbox.length >= maxQueuedMessages) outbox.shift();\n outbox.push(payload);\n return true;\n }\n\n function close(code?: number, reason?: string): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearPing();\n clearHandshake();\n clearSilence();\n clearNetworkWait();\n retries = 0;\n outbox.length = 0;\n if (failOpen) {\n const reject = failOpen;\n failOpen = null;\n settleOpen = null;\n reject(new Error(\"websocket_closed\"));\n }\n if (socket) {\n setStatus(\"closing\");\n closeSocket(socket, code, reason);\n socket = null;\n }\n setStatus(\"closed\");\n }\n\n /**\n * Close a socket without the \"closed before the connection is established\"\n * console warning.\n *\n * A socket still in `CONNECTING` cannot be closed cleanly — the browser\n * logs that warning on every attempt. React's StrictMode mounts, unmounts\n * and remounts each component in development, so the first socket is\n * always torn down mid-handshake and the message shows up in every dev\n * session of every app using the hook. Deferring the close to `onopen`\n * costs one round trip and keeps the console usable.\n */\n function closeSocket(ws: WebSocket, code?: number, reason?: string): void {\n if (ws.readyState === WebSocket.CONNECTING) {\n ws.onopen = () => ws.close(code, reason);\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n return;\n }\n ws.close(code, reason);\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearNetworkWait();\n retries = 0;\n closed = false;\n connect();\n }\n\n function setSilenceTimeout(ms: number): void {\n silenceWindow = Number.isFinite(ms) && ms > 0 ? ms : 0;\n if (socket?.readyState === WebSocket.OPEN) armSilence();\n else clearSilence();\n }\n\n connect();\n\n return {\n send,\n close,\n reconnect,\n setSilenceTimeout,\n opened,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":";;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GACb;EACJ;EACA,EAAG,MAAM,GAAM,CAAM;CACzB;CAEA,SAAS,KAAkB;EAQvB,AAPA,AAEI,OADA,aAAa,CAAU,GACV,OAEjB,EAAiB,GACjB,IAAU,GACV,IAAS,IACT,EAAQ;CACZ;CAEA,SAAS,GAAkB,GAAkB;EAEzC,AADA,IAAgB,OAAO,SAAS,CAAE,KAAK,IAAK,IAAI,IAAK,GACjD,GAAQ,eAAe,UAAU,OAAM,EAAW,IACjD,EAAa;CACtB;CAIA,OAFA,EAAQ,GAED;EACH;EACA;EACA;EACA;EACA;EACA,IAAI,SAAS;GACT,OAAO;EACX;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../hooks/use-latest-ref.cjs"),t=require("./create-web-socket.cjs");let n=require("react");function r(r,i={}){let{enabled:a=!0,protocols:o,maxRetries:s,initialBackoff:c,maxBackoff:l,jitter:u,handshakeTimeout:d,silenceTimeout:f,waitForOnline:p,pingInterval:m,respondToPing:h,queueWhileClosed:g,maxQueuedMessages:_}=i,[v,y]=(0,n.useState)(`idle`),[b,x]=(0,n.useState)(null),S=(0,n.useRef)(null),C=e.useLatestRef(i),w=Array.isArray(o)?o.join(`,`):o??``;return(0,n.useEffect)(()=>{if(!a||!r){y(`idle`);return}let e=C.current.parser!==void 0,n=C.current.onParseError!==void 0,i=t.createWebSocket(r,{protocols:C.current.protocols,maxRetries:s,initialBackoff:c,maxBackoff:l,jitter:u,handshakeTimeout:d,silenceTimeout:f,waitForOnline:p,pingInterval:m,pingPayload:C.current.pingPayload,respondToPing:h,pongPayload:C.current.pongPayload,queueWhileClosed:g,maxQueuedMessages:_,parser:e?e=>C.current.parser?.(e):void 0,onParseError:n?(e,t)=>C.current.onParseError?.(e,t):void 0,onStatusChange:y,onOpen:e=>C.current.onOpen?.(e),onClose:e=>C.current.onClose?.(e),onError:e=>C.current.onError?.(e),onReconnecting:(e,t)=>C.current.onReconnecting?.(e,t),onReconnected:()=>C.current.onReconnected?.(),onLost:e=>C.current.onLost?.(e),onMessage:e=>{x(e),C.current.onMessage?.(e)}});return S.current=
|
|
1
|
+
const e=require("../hooks/use-latest-ref.cjs"),t=require("./create-web-socket.cjs");let n=require("react");function r(r,i={}){let{enabled:a=!0,protocols:o,maxRetries:s,initialBackoff:c,maxBackoff:l,jitter:u,handshakeTimeout:d,silenceTimeout:f,waitForOnline:p,pingInterval:m,respondToPing:h,queueWhileClosed:g,maxQueuedMessages:_}=i,[v,y]=(0,n.useState)(`idle`),[b,x]=(0,n.useState)(null),S=(0,n.useRef)(null),C=e.useLatestRef(i),w=Array.isArray(o)?o.join(`,`):o??``;return(0,n.useEffect)(()=>{if(!a||!r){y(`idle`);return}let e=C.current.parser!==void 0,n=C.current.onParseError!==void 0,i=C.current.onValidationError!==void 0,o=t.createWebSocket(r,{protocols:C.current.protocols,maxRetries:s,initialBackoff:c,maxBackoff:l,jitter:u,handshakeTimeout:d,silenceTimeout:f,waitForOnline:p,pingInterval:m,pingPayload:C.current.pingPayload,respondToPing:h,pongPayload:C.current.pongPayload,queueWhileClosed:g,maxQueuedMessages:_,parser:e?e=>C.current.parser?.(e):void 0,onParseError:n?(e,t)=>C.current.onParseError?.(e,t):void 0,schema:C.current.schema,onValidationError:i?(e,t)=>C.current.onValidationError?.(e,t):void 0,onStatusChange:y,onOpen:e=>C.current.onOpen?.(e),onClose:e=>C.current.onClose?.(e),onError:e=>C.current.onError?.(e),onReconnecting:(e,t)=>C.current.onReconnecting?.(e,t),onReconnected:()=>C.current.onReconnected?.(),onLost:e=>C.current.onLost?.(e),onMessage:e=>{x(e),C.current.onMessage?.(e)}});return S.current=o,()=>{o.close(),S.current=null}},[r,a,w,s,c,l,u,d,f,p,m,h,g,_,C]),{status:v,lastMessage:b,send:(0,n.useCallback)(e=>S.current?.send(e)??!1,[]),reconnect:(0,n.useCallback)(()=>{S.current?.reconnect()},[]),setSilenceTimeout:(0,n.useCallback)(e=>{S.current?.setSilenceTimeout(e)},[])}}exports.useWebSocket=r;
|
|
2
2
|
//# sourceMappingURL=use-web-socket.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-web-socket.cjs","names":[],"sources":["../../src/ws/use-web-socket.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createWebSocket,\n type CreateWebSocketOptions,\n type WebSocketController,\n type WebSocketMessage,\n type WebSocketStatus,\n} from \"./create-web-socket\";\n\nexport interface UseWebSocketOptions<T> extends Omit<CreateWebSocketOptions<T>, \"onStatusChange\"> {\n /** When false, the socket is not opened. Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseWebSocketResult<T> {\n status: WebSocketStatus;\n /**\n * Last decoded frame received.\n *\n * A snapshot, not a stream: two frames arriving in the same tick collapse\n * into a single render and only the later one is ever visible. One server\n * action often emits several frames in a row, so anything that must see\n * every message has to use `onMessage`, which fires once per frame. Read\n * `lastMessage` for \"what is the current state\" rendering only.\n */\n lastMessage: WebSocketMessage<T> | null;\n /** Send a payload through the active connection. Returns false when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Force a reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For a server that announces its own heartbeat interval in the first frame,\n * so the tolerated silence is not hard-coded on both ends.\n */\n setSilenceTimeout: (ms: number) => void;\n}\n\n/**\n * React hook around {@link createWebSocket}. Manages the connection lifecycle\n * for the host component and tears it down on unmount.\n *\n * Every callback is read through a ref, so `onOpen` / `onMessage` / `onClose` /\n * `onError` / `onReconnecting` / `onReconnected` / `onLost` always run the\n * latest closure — an inline arrow function is fine and never reopens the\n * socket. Connection-shaping options (`protocols`, `maxRetries`,\n * `initialBackoff`, `maxBackoff`, `jitter`, `handshakeTimeout`,\n * `silenceTimeout`, `waitForOnline`, `pingInterval`, `queueWhileClosed`) are\n * baked into the connection, so changing one reopens it with the new value\n * rather than being silently ignored.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Status, last frame, and the `send` / `reconnect` controls.\n */\nexport function useWebSocket<T = unknown>(\n url: string,\n options: UseWebSocketOptions<T> = {},\n): UseWebSocketResult<T> {\n const {\n enabled = true,\n protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n } = options;\n const [status, setStatus] = useState<WebSocketStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<WebSocketMessage<T> | null>(null);\n const controllerRef = useRef<WebSocketController | null>(null);\n\n const optionsRef = useLatestRef(options);\n\n const protocolsKey = Array.isArray(protocols) ? protocols.join(\",\") : (protocols ?? \"\");\n\n useEffect(() => {\n if (!enabled || !url) {\n setStatus(\"idle\");\n return;\n }\n\n /*\n * Presence is read once, when the socket opens, and decides whether the\n * forwarder is passed at all. A forwarder is always truthy, so wrapping\n * an absent `parser` — or an absent `onParseError` — would tell\n * `decodeFrame` the caller had supplied one and silently pick the wrong\n * branch.\n */\n const hasParser = optionsRef.current.parser !== undefined;\n const hasParseError = optionsRef.current.onParseError !== undefined;\n\n const controller = createWebSocket<T>(url, {\n protocols: optionsRef.current.protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n pingPayload: optionsRef.current.pingPayload,\n respondToPing,\n pongPayload: optionsRef.current.pongPayload,\n queueWhileClosed,\n maxQueuedMessages,\n parser: hasParser ? (raw) => optionsRef.current.parser?.(raw) as T : undefined,\n onParseError: hasParseError\n ? (error, raw) => optionsRef.current.onParseError?.(error, raw)\n : undefined,\n onStatusChange: setStatus,\n onOpen: (event) => optionsRef.current.onOpen?.(event),\n onClose: (event) => optionsRef.current.onClose?.(event),\n onError: (event) => optionsRef.current.onError?.(event),\n onReconnecting: (attempt, total) => optionsRef.current.onReconnecting?.(attempt, total),\n onReconnected: () => optionsRef.current.onReconnected?.(),\n onLost: (reason) => optionsRef.current.onLost?.(reason),\n onMessage: (message) => {\n setLastMessage(message);\n optionsRef.current.onMessage?.(message);\n },\n });\n controllerRef.current = controller;\n\n return () => {\n controller.close();\n controllerRef.current = null;\n };\n }, [\n url,\n enabled,\n protocolsKey,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n optionsRef,\n ]);\n\n const send = useCallback((payload: string | Blob | BufferSource): boolean => {\n return controllerRef.current?.send(payload) ?? false;\n }, []);\n\n const reconnect = useCallback((): void => {\n controllerRef.current?.reconnect();\n }, []);\n\n const setSilenceTimeout = useCallback((ms: number): void => {\n controllerRef.current?.setSilenceTimeout(ms);\n }, []);\n\n return { status, lastMessage, send, reconnect, setSilenceTimeout };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-web-socket.cjs","names":[],"sources":["../../src/ws/use-web-socket.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createWebSocket,\n type CreateWebSocketOptions,\n type WebSocketController,\n type WebSocketMessage,\n type WebSocketStatus,\n} from \"./create-web-socket\";\n\nexport interface UseWebSocketOptions<T> extends Omit<CreateWebSocketOptions<T>, \"onStatusChange\"> {\n /** When false, the socket is not opened. Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseWebSocketResult<T> {\n status: WebSocketStatus;\n /**\n * Last decoded frame received.\n *\n * A snapshot, not a stream: two frames arriving in the same tick collapse\n * into a single render and only the later one is ever visible. One server\n * action often emits several frames in a row, so anything that must see\n * every message has to use `onMessage`, which fires once per frame. Read\n * `lastMessage` for \"what is the current state\" rendering only.\n */\n lastMessage: WebSocketMessage<T> | null;\n /** Send a payload through the active connection. Returns false when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Force a reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For a server that announces its own heartbeat interval in the first frame,\n * so the tolerated silence is not hard-coded on both ends.\n */\n setSilenceTimeout: (ms: number) => void;\n}\n\n/**\n * React hook around {@link createWebSocket}. Manages the connection lifecycle\n * for the host component and tears it down on unmount.\n *\n * Every callback is read through a ref, so `onOpen` / `onMessage` / `onClose` /\n * `onError` / `onReconnecting` / `onReconnected` / `onLost` always run the\n * latest closure — an inline arrow function is fine and never reopens the\n * socket. Connection-shaping options (`protocols`, `maxRetries`,\n * `initialBackoff`, `maxBackoff`, `jitter`, `handshakeTimeout`,\n * `silenceTimeout`, `waitForOnline`, `pingInterval`, `queueWhileClosed`) are\n * baked into the connection, so changing one reopens it with the new value\n * rather than being silently ignored.\n *\n * `schema` is read when the socket opens, so declare it outside the component\n * (or memoize it): a schema built inline is a new object on every render, and\n * the one in force is whichever existed at the last open.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Status, last frame, and the `send` / `reconnect` controls.\n */\nexport function useWebSocket<T = unknown>(\n url: string,\n options: UseWebSocketOptions<T> = {},\n): UseWebSocketResult<T> {\n const {\n enabled = true,\n protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n } = options;\n const [status, setStatus] = useState<WebSocketStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<WebSocketMessage<T> | null>(null);\n const controllerRef = useRef<WebSocketController | null>(null);\n\n const optionsRef = useLatestRef(options);\n\n const protocolsKey = Array.isArray(protocols) ? protocols.join(\",\") : (protocols ?? \"\");\n\n useEffect(() => {\n if (!enabled || !url) {\n setStatus(\"idle\");\n return;\n }\n\n /*\n * Presence is read once, when the socket opens, and decides whether the\n * forwarder is passed at all. A forwarder is always truthy, so wrapping\n * an absent `parser` — or an absent `onParseError` — would tell\n * `decodeFrame` the caller had supplied one and silently pick the wrong\n * branch.\n */\n const hasParser = optionsRef.current.parser !== undefined;\n const hasParseError = optionsRef.current.onParseError !== undefined;\n const hasValidationError = optionsRef.current.onValidationError !== undefined;\n\n const controller = createWebSocket<T>(url, {\n protocols: optionsRef.current.protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n pingPayload: optionsRef.current.pingPayload,\n respondToPing,\n pongPayload: optionsRef.current.pongPayload,\n queueWhileClosed,\n maxQueuedMessages,\n parser: hasParser ? (raw) => optionsRef.current.parser?.(raw) as T : undefined,\n onParseError: hasParseError\n ? (error, raw) => optionsRef.current.onParseError?.(error, raw)\n : undefined,\n schema: optionsRef.current.schema,\n onValidationError: hasValidationError\n ? (issues, raw) => optionsRef.current.onValidationError?.(issues, raw)\n : undefined,\n onStatusChange: setStatus,\n onOpen: (event) => optionsRef.current.onOpen?.(event),\n onClose: (event) => optionsRef.current.onClose?.(event),\n onError: (event) => optionsRef.current.onError?.(event),\n onReconnecting: (attempt, total) => optionsRef.current.onReconnecting?.(attempt, total),\n onReconnected: () => optionsRef.current.onReconnected?.(),\n onLost: (reason) => optionsRef.current.onLost?.(reason),\n onMessage: (message) => {\n setLastMessage(message);\n optionsRef.current.onMessage?.(message);\n },\n });\n controllerRef.current = controller;\n\n return () => {\n controller.close();\n controllerRef.current = null;\n };\n }, [\n url,\n enabled,\n protocolsKey,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n optionsRef,\n ]);\n\n const send = useCallback((payload: string | Blob | BufferSource): boolean => {\n return controllerRef.current?.send(payload) ?? false;\n }, []);\n\n const reconnect = useCallback((): void => {\n controllerRef.current?.reconnect();\n }, []);\n\n const setSilenceTimeout = useCallback((ms: number): void => {\n controllerRef.current?.setSilenceTimeout(ms);\n }, []);\n\n return { status, lastMessage, send, reconnect, setSilenceTimeout };\n}\n"],"mappings":"2GA6DA,SAAgB,EACZ,EACA,EAAkC,CAAC,EACd,CACrB,GAAM,CACF,UAAU,GACV,YACA,aACA,iBACA,aACA,SACA,mBACA,iBACA,gBACA,eACA,gBACA,mBACA,qBACA,EACE,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAA0B,MAAM,EACtD,CAAC,EAAa,IAAA,EAAkB,EAAA,SAAA,CAAqC,IAAI,EACzE,GAAA,EAAgB,EAAA,OAAA,CAAmC,IAAI,EAEvD,EAAa,EAAA,aAAa,CAAO,EAEjC,EAAe,MAAM,QAAQ,CAAS,EAAI,EAAU,KAAK,GAAG,EAAK,GAAa,GA0FpF,OAxFA,EAAA,EAAA,UAAA,KAAgB,CACZ,GAAI,CAAC,GAAW,CAAC,EAAK,CAClB,EAAU,MAAM,EAChB,MACJ,CASA,IAAM,EAAY,EAAW,QAAQ,SAAW,IAAA,GAC1C,EAAgB,EAAW,QAAQ,eAAiB,IAAA,GACpD,EAAqB,EAAW,QAAQ,oBAAsB,IAAA,GAE9D,EAAa,EAAA,gBAAmB,EAAK,CACvC,UAAW,EAAW,QAAQ,UAC9B,aACA,iBACA,aACA,SACA,mBACA,iBACA,gBACA,eACA,YAAa,EAAW,QAAQ,YAChC,gBACA,YAAa,EAAW,QAAQ,YAChC,mBACA,oBACA,OAAQ,EAAa,GAAQ,EAAW,QAAQ,SAAS,CAAG,EAAS,IAAA,GACrE,aAAc,GACP,EAAO,IAAQ,EAAW,QAAQ,eAAe,EAAO,CAAG,EAC5D,IAAA,GACN,OAAQ,EAAW,QAAQ,OAC3B,kBAAmB,GACZ,EAAQ,IAAQ,EAAW,QAAQ,oBAAoB,EAAQ,CAAG,EACnE,IAAA,GACN,eAAgB,EAChB,OAAS,GAAU,EAAW,QAAQ,SAAS,CAAK,EACpD,QAAU,GAAU,EAAW,QAAQ,UAAU,CAAK,EACtD,QAAU,GAAU,EAAW,QAAQ,UAAU,CAAK,EACtD,gBAAiB,EAAS,IAAU,EAAW,QAAQ,iBAAiB,EAAS,CAAK,EACtF,kBAAqB,EAAW,QAAQ,gBAAgB,EACxD,OAAS,GAAW,EAAW,QAAQ,SAAS,CAAM,EACtD,UAAY,GAAY,CACpB,EAAe,CAAO,EACtB,EAAW,QAAQ,YAAY,CAAO,CAC1C,CACJ,CAAC,EAGD,MAFA,GAAc,QAAU,MAEX,CACT,EAAW,MAAM,EACjB,EAAc,QAAU,IAC5B,CACJ,EAAG,CACC,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACJ,CAAC,EAcM,CAAE,SAAQ,cAAa,MAAA,EAZjB,EAAA,YAAA,CAAa,GACf,EAAc,SAAS,KAAK,CAAO,GAAK,GAChD,CAAC,CAU0B,EAAM,WAAA,EARlB,EAAA,YAAA,KAAwB,CACtC,EAAc,SAAS,UAAU,CACrC,EAAG,CAAC,CAMgC,EAAW,mBAAA,EAJrB,EAAA,YAAA,CAAa,GAAqB,CACxD,EAAc,SAAS,kBAAkB,CAAE,CAC/C,EAAG,CAAC,CAE2C,CAAkB,CACrE"}
|
|
@@ -9,7 +9,7 @@ function o(o, s = {}) {
|
|
|
9
9
|
S("idle");
|
|
10
10
|
return;
|
|
11
11
|
}
|
|
12
|
-
let e = E.current.parser !== void 0, n = E.current.onParseError !== void 0, r = t(o, {
|
|
12
|
+
let e = E.current.parser !== void 0, n = E.current.onParseError !== void 0, r = E.current.onValidationError !== void 0, i = t(o, {
|
|
13
13
|
protocols: E.current.protocols,
|
|
14
14
|
maxRetries: u,
|
|
15
15
|
initialBackoff: d,
|
|
@@ -26,6 +26,8 @@ function o(o, s = {}) {
|
|
|
26
26
|
maxQueuedMessages: b,
|
|
27
27
|
parser: e ? (e) => E.current.parser?.(e) : void 0,
|
|
28
28
|
onParseError: n ? (e, t) => E.current.onParseError?.(e, t) : void 0,
|
|
29
|
+
schema: E.current.schema,
|
|
30
|
+
onValidationError: r ? (e, t) => E.current.onValidationError?.(e, t) : void 0,
|
|
29
31
|
onStatusChange: S,
|
|
30
32
|
onOpen: (e) => E.current.onOpen?.(e),
|
|
31
33
|
onClose: (e) => E.current.onClose?.(e),
|
|
@@ -37,8 +39,8 @@ function o(o, s = {}) {
|
|
|
37
39
|
w(e), E.current.onMessage?.(e);
|
|
38
40
|
}
|
|
39
41
|
});
|
|
40
|
-
return T.current =
|
|
41
|
-
|
|
42
|
+
return T.current = i, () => {
|
|
43
|
+
i.close(), T.current = null;
|
|
42
44
|
};
|
|
43
45
|
}, [
|
|
44
46
|
o,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-web-socket.js","names":[],"sources":["../../src/ws/use-web-socket.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createWebSocket,\n type CreateWebSocketOptions,\n type WebSocketController,\n type WebSocketMessage,\n type WebSocketStatus,\n} from \"./create-web-socket\";\n\nexport interface UseWebSocketOptions<T> extends Omit<CreateWebSocketOptions<T>, \"onStatusChange\"> {\n /** When false, the socket is not opened. Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseWebSocketResult<T> {\n status: WebSocketStatus;\n /**\n * Last decoded frame received.\n *\n * A snapshot, not a stream: two frames arriving in the same tick collapse\n * into a single render and only the later one is ever visible. One server\n * action often emits several frames in a row, so anything that must see\n * every message has to use `onMessage`, which fires once per frame. Read\n * `lastMessage` for \"what is the current state\" rendering only.\n */\n lastMessage: WebSocketMessage<T> | null;\n /** Send a payload through the active connection. Returns false when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Force a reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For a server that announces its own heartbeat interval in the first frame,\n * so the tolerated silence is not hard-coded on both ends.\n */\n setSilenceTimeout: (ms: number) => void;\n}\n\n/**\n * React hook around {@link createWebSocket}. Manages the connection lifecycle\n * for the host component and tears it down on unmount.\n *\n * Every callback is read through a ref, so `onOpen` / `onMessage` / `onClose` /\n * `onError` / `onReconnecting` / `onReconnected` / `onLost` always run the\n * latest closure — an inline arrow function is fine and never reopens the\n * socket. Connection-shaping options (`protocols`, `maxRetries`,\n * `initialBackoff`, `maxBackoff`, `jitter`, `handshakeTimeout`,\n * `silenceTimeout`, `waitForOnline`, `pingInterval`, `queueWhileClosed`) are\n * baked into the connection, so changing one reopens it with the new value\n * rather than being silently ignored.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Status, last frame, and the `send` / `reconnect` controls.\n */\nexport function useWebSocket<T = unknown>(\n url: string,\n options: UseWebSocketOptions<T> = {},\n): UseWebSocketResult<T> {\n const {\n enabled = true,\n protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n } = options;\n const [status, setStatus] = useState<WebSocketStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<WebSocketMessage<T> | null>(null);\n const controllerRef = useRef<WebSocketController | null>(null);\n\n const optionsRef = useLatestRef(options);\n\n const protocolsKey = Array.isArray(protocols) ? protocols.join(\",\") : (protocols ?? \"\");\n\n useEffect(() => {\n if (!enabled || !url) {\n setStatus(\"idle\");\n return;\n }\n\n /*\n * Presence is read once, when the socket opens, and decides whether the\n * forwarder is passed at all. A forwarder is always truthy, so wrapping\n * an absent `parser` — or an absent `onParseError` — would tell\n * `decodeFrame` the caller had supplied one and silently pick the wrong\n * branch.\n */\n const hasParser = optionsRef.current.parser !== undefined;\n const hasParseError = optionsRef.current.onParseError !== undefined;\n\n const controller = createWebSocket<T>(url, {\n protocols: optionsRef.current.protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n pingPayload: optionsRef.current.pingPayload,\n respondToPing,\n pongPayload: optionsRef.current.pongPayload,\n queueWhileClosed,\n maxQueuedMessages,\n parser: hasParser ? (raw) => optionsRef.current.parser?.(raw) as T : undefined,\n onParseError: hasParseError\n ? (error, raw) => optionsRef.current.onParseError?.(error, raw)\n : undefined,\n onStatusChange: setStatus,\n onOpen: (event) => optionsRef.current.onOpen?.(event),\n onClose: (event) => optionsRef.current.onClose?.(event),\n onError: (event) => optionsRef.current.onError?.(event),\n onReconnecting: (attempt, total) => optionsRef.current.onReconnecting?.(attempt, total),\n onReconnected: () => optionsRef.current.onReconnected?.(),\n onLost: (reason) => optionsRef.current.onLost?.(reason),\n onMessage: (message) => {\n setLastMessage(message);\n optionsRef.current.onMessage?.(message);\n },\n });\n controllerRef.current = controller;\n\n return () => {\n controller.close();\n controllerRef.current = null;\n };\n }, [\n url,\n enabled,\n protocolsKey,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n optionsRef,\n ]);\n\n const send = useCallback((payload: string | Blob | BufferSource): boolean => {\n return controllerRef.current?.send(payload) ?? false;\n }, []);\n\n const reconnect = useCallback((): void => {\n controllerRef.current?.reconnect();\n }, []);\n\n const setSilenceTimeout = useCallback((ms: number): void => {\n controllerRef.current?.setSilenceTimeout(ms);\n }, []);\n\n return { status, lastMessage, send, reconnect, setSilenceTimeout };\n}\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"use-web-socket.js","names":[],"sources":["../../src/ws/use-web-socket.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createWebSocket,\n type CreateWebSocketOptions,\n type WebSocketController,\n type WebSocketMessage,\n type WebSocketStatus,\n} from \"./create-web-socket\";\n\nexport interface UseWebSocketOptions<T> extends Omit<CreateWebSocketOptions<T>, \"onStatusChange\"> {\n /** When false, the socket is not opened. Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseWebSocketResult<T> {\n status: WebSocketStatus;\n /**\n * Last decoded frame received.\n *\n * A snapshot, not a stream: two frames arriving in the same tick collapse\n * into a single render and only the later one is ever visible. One server\n * action often emits several frames in a row, so anything that must see\n * every message has to use `onMessage`, which fires once per frame. Read\n * `lastMessage` for \"what is the current state\" rendering only.\n */\n lastMessage: WebSocketMessage<T> | null;\n /** Send a payload through the active connection. Returns false when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Force a reconnect, resetting the retry counter. */\n reconnect: () => void;\n /**\n * Change the silence watchdog at runtime, in ms. `0` disables it.\n *\n * For a server that announces its own heartbeat interval in the first frame,\n * so the tolerated silence is not hard-coded on both ends.\n */\n setSilenceTimeout: (ms: number) => void;\n}\n\n/**\n * React hook around {@link createWebSocket}. Manages the connection lifecycle\n * for the host component and tears it down on unmount.\n *\n * Every callback is read through a ref, so `onOpen` / `onMessage` / `onClose` /\n * `onError` / `onReconnecting` / `onReconnected` / `onLost` always run the\n * latest closure — an inline arrow function is fine and never reopens the\n * socket. Connection-shaping options (`protocols`, `maxRetries`,\n * `initialBackoff`, `maxBackoff`, `jitter`, `handshakeTimeout`,\n * `silenceTimeout`, `waitForOnline`, `pingInterval`, `queueWhileClosed`) are\n * baked into the connection, so changing one reopens it with the new value\n * rather than being silently ignored.\n *\n * `schema` is read when the socket opens, so declare it outside the component\n * (or memoize it): a schema built inline is a new object on every render, and\n * the one in force is whichever existed at the last open.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Status, last frame, and the `send` / `reconnect` controls.\n */\nexport function useWebSocket<T = unknown>(\n url: string,\n options: UseWebSocketOptions<T> = {},\n): UseWebSocketResult<T> {\n const {\n enabled = true,\n protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n } = options;\n const [status, setStatus] = useState<WebSocketStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<WebSocketMessage<T> | null>(null);\n const controllerRef = useRef<WebSocketController | null>(null);\n\n const optionsRef = useLatestRef(options);\n\n const protocolsKey = Array.isArray(protocols) ? protocols.join(\",\") : (protocols ?? \"\");\n\n useEffect(() => {\n if (!enabled || !url) {\n setStatus(\"idle\");\n return;\n }\n\n /*\n * Presence is read once, when the socket opens, and decides whether the\n * forwarder is passed at all. A forwarder is always truthy, so wrapping\n * an absent `parser` — or an absent `onParseError` — would tell\n * `decodeFrame` the caller had supplied one and silently pick the wrong\n * branch.\n */\n const hasParser = optionsRef.current.parser !== undefined;\n const hasParseError = optionsRef.current.onParseError !== undefined;\n const hasValidationError = optionsRef.current.onValidationError !== undefined;\n\n const controller = createWebSocket<T>(url, {\n protocols: optionsRef.current.protocols,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n pingPayload: optionsRef.current.pingPayload,\n respondToPing,\n pongPayload: optionsRef.current.pongPayload,\n queueWhileClosed,\n maxQueuedMessages,\n parser: hasParser ? (raw) => optionsRef.current.parser?.(raw) as T : undefined,\n onParseError: hasParseError\n ? (error, raw) => optionsRef.current.onParseError?.(error, raw)\n : undefined,\n schema: optionsRef.current.schema,\n onValidationError: hasValidationError\n ? (issues, raw) => optionsRef.current.onValidationError?.(issues, raw)\n : undefined,\n onStatusChange: setStatus,\n onOpen: (event) => optionsRef.current.onOpen?.(event),\n onClose: (event) => optionsRef.current.onClose?.(event),\n onError: (event) => optionsRef.current.onError?.(event),\n onReconnecting: (attempt, total) => optionsRef.current.onReconnecting?.(attempt, total),\n onReconnected: () => optionsRef.current.onReconnected?.(),\n onLost: (reason) => optionsRef.current.onLost?.(reason),\n onMessage: (message) => {\n setLastMessage(message);\n optionsRef.current.onMessage?.(message);\n },\n });\n controllerRef.current = controller;\n\n return () => {\n controller.close();\n controllerRef.current = null;\n };\n }, [\n url,\n enabled,\n protocolsKey,\n maxRetries,\n initialBackoff,\n maxBackoff,\n jitter,\n handshakeTimeout,\n silenceTimeout,\n waitForOnline,\n pingInterval,\n respondToPing,\n queueWhileClosed,\n maxQueuedMessages,\n optionsRef,\n ]);\n\n const send = useCallback((payload: string | Blob | BufferSource): boolean => {\n return controllerRef.current?.send(payload) ?? false;\n }, []);\n\n const reconnect = useCallback((): void => {\n controllerRef.current?.reconnect();\n }, []);\n\n const setSilenceTimeout = useCallback((ms: number): void => {\n controllerRef.current?.setSilenceTimeout(ms);\n }, []);\n\n return { status, lastMessage, send, reconnect, setSilenceTimeout };\n}\n"],"mappings":";;;;AA6DA,SAAgB,EACZ,GACA,IAAkC,CAAC,GACd;CACrB,IAAM,EACF,aAAU,IACV,cACA,eACA,mBACA,eACA,WACA,qBACA,mBACA,kBACA,iBACA,kBACA,qBACA,yBACA,GACE,CAAC,GAAQ,KAAa,EAA0B,MAAM,GACtD,CAAC,GAAa,KAAkB,EAAqC,IAAI,GACzE,IAAgB,EAAmC,IAAI,GAEvD,IAAa,EAAa,CAAO,GAEjC,IAAe,MAAM,QAAQ,CAAS,IAAI,EAAU,KAAK,GAAG,IAAK,KAAa;CA0FpF,OAxFA,QAAgB;EACZ,IAAI,CAAC,KAAW,CAAC,GAAK;GAClB,EAAU,MAAM;GAChB;EACJ;EASA,IAAM,IAAY,EAAW,QAAQ,WAAW,KAAA,GAC1C,IAAgB,EAAW,QAAQ,iBAAiB,KAAA,GACpD,IAAqB,EAAW,QAAQ,sBAAsB,KAAA,GAE9D,IAAa,EAAmB,GAAK;GACvC,WAAW,EAAW,QAAQ;GAC9B;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,aAAa,EAAW,QAAQ;GAChC;GACA,aAAa,EAAW,QAAQ;GAChC;GACA;GACA,QA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