@kyneta/websocket-transport 1.3.1 → 1.5.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/browser.d.ts +31 -30
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +2 -15
- package/dist/bun.d.ts +18 -18
- package/dist/bun.d.ts.map +1 -0
- package/dist/bun.js +95 -43
- package/dist/bun.js.map +1 -1
- package/dist/client-transport-B2V7s2VP.js +525 -0
- package/dist/client-transport-B2V7s2VP.js.map +1 -0
- package/dist/client-transport-D3tYQYrS.d.ts +134 -0
- package/dist/client-transport-D3tYQYrS.d.ts.map +1 -0
- package/dist/server.d.ts +121 -118
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +304 -305
- package/dist/server.js.map +1 -1
- package/dist/{types-D0lbeevu.d.ts → types-c1S_xIRG.d.ts} +78 -69
- package/dist/types-c1S_xIRG.d.ts.map +1 -0
- package/package.json +13 -12
- package/src/__tests__/client-transport.test.ts +8 -9
- package/src/browser.ts +3 -3
- package/src/bun-websocket.ts +3 -3
- package/src/client-transport.ts +42 -17
- package/src/connection.ts +38 -13
- package/src/server-transport.ts +9 -24
- package/src/server.ts +5 -1
- package/src/service-client.ts +2 -2
- package/src/types.ts +17 -12
- package/dist/browser.js.map +0 -1
- package/dist/chunk-YZQF5RLV.js +0 -614
- package/dist/chunk-YZQF5RLV.js.map +0 -1
- package/dist/client-transport-DUAFjVbh.d.ts +0 -132
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
import { DEFAULT_RECONNECT, Transport, computeBackoffDelay } from "@kyneta/transport";
|
|
2
|
+
import { createObservableProgram } from "@kyneta/machine";
|
|
3
|
+
import { FragmentReassembler, applyInboundAliasing, applyOutboundAliasing, createFrameIdCounter, decodeBinaryWires, emptyAliasState, encodeWireFrameAndSend } from "@kyneta/wire";
|
|
4
|
+
//#region src/client-program.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create the websocket client connection lifecycle program — a pure Mealy machine.
|
|
7
|
+
*
|
|
8
|
+
* The returned `Program<WsClientMsg, WebsocketClientState, WsClientEffect>`
|
|
9
|
+
* encodes every state transition and effect as inspectable data. The imperative
|
|
10
|
+
* shell interprets `WsClientEffect` as actual I/O.
|
|
11
|
+
*/
|
|
12
|
+
function createWsClientProgram(options = {}) {
|
|
13
|
+
const { jitterFn = () => Math.random() * 1e3 } = options;
|
|
14
|
+
const reconnect = {
|
|
15
|
+
...DEFAULT_RECONNECT,
|
|
16
|
+
...options.reconnect
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Attempt to transition into reconnecting, or give up and disconnect.
|
|
20
|
+
*
|
|
21
|
+
* Pure — computes the next state and effects from the current attempt
|
|
22
|
+
* count and reconnect configuration. Returns a tuple suitable for
|
|
23
|
+
* spreading into an `update` return.
|
|
24
|
+
*/
|
|
25
|
+
function tryReconnect(currentAttempt, reason, ...extraEffects) {
|
|
26
|
+
if (!reconnect.enabled) return [{
|
|
27
|
+
status: "disconnected",
|
|
28
|
+
reason
|
|
29
|
+
}, ...extraEffects];
|
|
30
|
+
if (currentAttempt >= reconnect.maxAttempts) return [{
|
|
31
|
+
status: "disconnected",
|
|
32
|
+
reason: {
|
|
33
|
+
type: "max-retries-exceeded",
|
|
34
|
+
attempts: currentAttempt
|
|
35
|
+
}
|
|
36
|
+
}, ...extraEffects];
|
|
37
|
+
const delay = computeBackoffDelay(currentAttempt + 1, reconnect.baseDelay, reconnect.maxDelay, jitterFn());
|
|
38
|
+
return [
|
|
39
|
+
{
|
|
40
|
+
status: "reconnecting",
|
|
41
|
+
attempt: currentAttempt + 1,
|
|
42
|
+
nextAttemptMs: delay
|
|
43
|
+
},
|
|
44
|
+
...extraEffects,
|
|
45
|
+
{
|
|
46
|
+
type: "start-reconnect-timer",
|
|
47
|
+
delayMs: delay
|
|
48
|
+
}
|
|
49
|
+
];
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
init: [{ status: "disconnected" }],
|
|
53
|
+
update(msg, model) {
|
|
54
|
+
switch (msg.type) {
|
|
55
|
+
case "start":
|
|
56
|
+
if (model.status !== "disconnected") return [model];
|
|
57
|
+
return [{
|
|
58
|
+
status: "connecting",
|
|
59
|
+
attempt: 1
|
|
60
|
+
}, {
|
|
61
|
+
type: "create-websocket",
|
|
62
|
+
attempt: 1
|
|
63
|
+
}];
|
|
64
|
+
case "socket-opened":
|
|
65
|
+
if (model.status !== "connecting") return [model];
|
|
66
|
+
return [{ status: "connected" }, { type: "start-keepalive" }];
|
|
67
|
+
case "server-ready":
|
|
68
|
+
if (model.status === "ready") return [model];
|
|
69
|
+
if (model.status === "connected") return [{ status: "ready" }, { type: "add-channel-and-establish" }];
|
|
70
|
+
if (model.status === "connecting") return [
|
|
71
|
+
{ status: "ready" },
|
|
72
|
+
{ type: "start-keepalive" },
|
|
73
|
+
{ type: "add-channel-and-establish" }
|
|
74
|
+
];
|
|
75
|
+
return [model];
|
|
76
|
+
case "socket-closed": {
|
|
77
|
+
const reason = {
|
|
78
|
+
type: "closed",
|
|
79
|
+
code: msg.code,
|
|
80
|
+
reason: msg.reason
|
|
81
|
+
};
|
|
82
|
+
if (model.status === "connected") return tryReconnect(0, reason, { type: "stop-keepalive" });
|
|
83
|
+
if (model.status === "ready") return tryReconnect(0, reason, { type: "stop-keepalive" }, { type: "remove-channel" });
|
|
84
|
+
return [model];
|
|
85
|
+
}
|
|
86
|
+
case "socket-error": {
|
|
87
|
+
const reason = {
|
|
88
|
+
type: "error",
|
|
89
|
+
error: msg.error
|
|
90
|
+
};
|
|
91
|
+
if (model.status === "connecting") return tryReconnect(model.attempt, reason);
|
|
92
|
+
if (model.status === "connected") return tryReconnect(0, reason, { type: "stop-keepalive" });
|
|
93
|
+
if (model.status === "ready") return tryReconnect(0, reason, { type: "stop-keepalive" }, { type: "remove-channel" });
|
|
94
|
+
return [model];
|
|
95
|
+
}
|
|
96
|
+
case "reconnect-timer-fired":
|
|
97
|
+
if (model.status !== "reconnecting") return [model];
|
|
98
|
+
return [{
|
|
99
|
+
status: "connecting",
|
|
100
|
+
attempt: model.attempt
|
|
101
|
+
}, {
|
|
102
|
+
type: "create-websocket",
|
|
103
|
+
attempt: model.attempt
|
|
104
|
+
}];
|
|
105
|
+
case "stop": {
|
|
106
|
+
if (model.status === "disconnected") return [model];
|
|
107
|
+
const effects = [{ type: "cancel-reconnect-timer" }];
|
|
108
|
+
if (model.status === "connecting") effects.push({ type: "close-websocket" });
|
|
109
|
+
if (model.status === "connected") effects.push({ type: "close-websocket" }, { type: "stop-keepalive" });
|
|
110
|
+
if (model.status === "ready") effects.push({ type: "close-websocket" }, { type: "stop-keepalive" }, { type: "remove-channel" });
|
|
111
|
+
return [{
|
|
112
|
+
status: "disconnected",
|
|
113
|
+
reason: { type: "intentional" }
|
|
114
|
+
}, ...effects];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
//#endregion
|
|
121
|
+
//#region src/types.ts
|
|
122
|
+
/**
|
|
123
|
+
* WebSocket readyState constants per the WHATWG WebSocket spec.
|
|
124
|
+
* Replaces references to `WebSocket.CONNECTING`, `WebSocket.OPEN`, etc.
|
|
125
|
+
* so that shared code never depends on the browser global.
|
|
126
|
+
*/
|
|
127
|
+
const READY_STATE = {
|
|
128
|
+
CONNECTING: 0,
|
|
129
|
+
OPEN: 1,
|
|
130
|
+
CLOSING: 2,
|
|
131
|
+
CLOSED: 3
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Wrap a standard `WebSocket` (browser or Node.js `ws` via `ws` package
|
|
135
|
+
* in `WebSocket`-compatible mode) into the `Socket` interface.
|
|
136
|
+
*
|
|
137
|
+
* Handles `ArrayBuffer`, `Blob`, and string messages.
|
|
138
|
+
*/
|
|
139
|
+
function wrapStandardWebsocket(ws) {
|
|
140
|
+
return {
|
|
141
|
+
send(data) {
|
|
142
|
+
ws.send(data);
|
|
143
|
+
},
|
|
144
|
+
close(code, reason) {
|
|
145
|
+
ws.close(code, reason);
|
|
146
|
+
},
|
|
147
|
+
onMessage(handler) {
|
|
148
|
+
ws.addEventListener("message", (event) => {
|
|
149
|
+
if (event.data instanceof ArrayBuffer) handler(new Uint8Array(event.data));
|
|
150
|
+
else if (typeof Blob !== "undefined" && event.data instanceof Blob) event.data.arrayBuffer().then((buffer) => {
|
|
151
|
+
handler(new Uint8Array(buffer));
|
|
152
|
+
});
|
|
153
|
+
else handler(event.data);
|
|
154
|
+
});
|
|
155
|
+
},
|
|
156
|
+
onClose(handler) {
|
|
157
|
+
ws.addEventListener("close", (event) => {
|
|
158
|
+
handler(event.code, event.reason);
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
onError(handler) {
|
|
162
|
+
ws.addEventListener("error", (_event) => {
|
|
163
|
+
handler(/* @__PURE__ */ new Error("WebSocket error"));
|
|
164
|
+
});
|
|
165
|
+
},
|
|
166
|
+
get readyState() {
|
|
167
|
+
switch (ws.readyState) {
|
|
168
|
+
case READY_STATE.CONNECTING: return "connecting";
|
|
169
|
+
case READY_STATE.OPEN: return "open";
|
|
170
|
+
case READY_STATE.CLOSING: return "closing";
|
|
171
|
+
case READY_STATE.CLOSED: return "closed";
|
|
172
|
+
default: return "closed";
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Wrap a Node.js `ws` library WebSocket into the `Socket` interface.
|
|
179
|
+
*
|
|
180
|
+
* Handles `Buffer` → `Uint8Array` conversion for binary messages.
|
|
181
|
+
*/
|
|
182
|
+
function wrapNodeWebsocket(ws) {
|
|
183
|
+
const CONNECTING = 0;
|
|
184
|
+
const OPEN = 1;
|
|
185
|
+
const CLOSING = 2;
|
|
186
|
+
return {
|
|
187
|
+
send(data) {
|
|
188
|
+
ws.send(data);
|
|
189
|
+
},
|
|
190
|
+
close(code, reason) {
|
|
191
|
+
ws.close(code, reason);
|
|
192
|
+
},
|
|
193
|
+
onMessage(handler) {
|
|
194
|
+
ws.on("message", (data, isBinary) => {
|
|
195
|
+
if (isBinary) if (data instanceof ArrayBuffer) handler(new Uint8Array(data));
|
|
196
|
+
else if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) handler(new Uint8Array(data));
|
|
197
|
+
else handler(new Uint8Array(data));
|
|
198
|
+
else if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) handler(data.toString("utf-8"));
|
|
199
|
+
else handler(data);
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
onClose(handler) {
|
|
203
|
+
ws.on("close", (code, reason) => {
|
|
204
|
+
handler(code, reason.toString());
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
onError(handler) {
|
|
208
|
+
ws.on("error", handler);
|
|
209
|
+
},
|
|
210
|
+
get readyState() {
|
|
211
|
+
switch (ws.readyState) {
|
|
212
|
+
case CONNECTING: return "connecting";
|
|
213
|
+
case OPEN: return "open";
|
|
214
|
+
case CLOSING: return "closing";
|
|
215
|
+
default: return "closed";
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
//#region src/client-transport.ts
|
|
222
|
+
/**
|
|
223
|
+
* Default fragment threshold in bytes.
|
|
224
|
+
* AWS API Gateway has a 128KB limit, so 100KB provides a safe margin.
|
|
225
|
+
*/
|
|
226
|
+
const DEFAULT_FRAGMENT_THRESHOLD = 100 * 1024;
|
|
227
|
+
/**
|
|
228
|
+
* Websocket client network transport for @kyneta/exchange.
|
|
229
|
+
*
|
|
230
|
+
* Connects to a Websocket server, sends and receives ChannelMsg via
|
|
231
|
+
* the kyneta wire format (CBOR codec + framing + fragmentation).
|
|
232
|
+
*
|
|
233
|
+
* Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —
|
|
234
|
+
* a pure Mealy machine whose transitions are deterministically testable.
|
|
235
|
+
* This class is the imperative shell that interprets data effects as I/O.
|
|
236
|
+
*
|
|
237
|
+
* Prefer the factory functions for construction:
|
|
238
|
+
* - `createWebsocketClient()` — browser-to-server (from `./browser`)
|
|
239
|
+
* - `createServiceWebsocketClient()` — service-to-service with headers (from `./server`)
|
|
240
|
+
*/
|
|
241
|
+
var WebsocketClientTransport = class extends Transport {
|
|
242
|
+
#peerId;
|
|
243
|
+
#options;
|
|
244
|
+
#WebSocketImpl;
|
|
245
|
+
#handle;
|
|
246
|
+
#socket;
|
|
247
|
+
#serverChannel;
|
|
248
|
+
#keepaliveTimer;
|
|
249
|
+
#reconnectTimer;
|
|
250
|
+
#fragmentThreshold;
|
|
251
|
+
#reassembler;
|
|
252
|
+
#aliasState = emptyAliasState();
|
|
253
|
+
constructor(options) {
|
|
254
|
+
super({ transportType: "websocket-client" });
|
|
255
|
+
this.#options = options;
|
|
256
|
+
this.#WebSocketImpl = options.WebSocket;
|
|
257
|
+
this.#fragmentThreshold = options.fragmentThreshold ?? 102400;
|
|
258
|
+
this.#reassembler = new FragmentReassembler({ timeoutMs: 1e4 });
|
|
259
|
+
const program = createWsClientProgram({ reconnect: options.reconnect });
|
|
260
|
+
this.#handle = createObservableProgram(program, (effect, dispatch) => {
|
|
261
|
+
this.#executeEffect(effect, dispatch);
|
|
262
|
+
});
|
|
263
|
+
this.#setupLifecycleEvents();
|
|
264
|
+
}
|
|
265
|
+
#executeEffect(effect, dispatch) {
|
|
266
|
+
switch (effect.type) {
|
|
267
|
+
case "create-websocket":
|
|
268
|
+
this.#doCreateWebsocket(dispatch);
|
|
269
|
+
break;
|
|
270
|
+
case "close-websocket":
|
|
271
|
+
if (this.#socket) {
|
|
272
|
+
this.#socket.close(1e3, "Client disconnecting");
|
|
273
|
+
this.#socket = void 0;
|
|
274
|
+
}
|
|
275
|
+
break;
|
|
276
|
+
case "add-channel-and-establish":
|
|
277
|
+
if (this.#serverChannel) {
|
|
278
|
+
this.removeChannel(this.#serverChannel.channelId);
|
|
279
|
+
this.#serverChannel = void 0;
|
|
280
|
+
}
|
|
281
|
+
this.#reassembler.reset();
|
|
282
|
+
this.#serverChannel = this.addChannel();
|
|
283
|
+
this.establishChannel(this.#serverChannel.channelId);
|
|
284
|
+
break;
|
|
285
|
+
case "remove-channel":
|
|
286
|
+
if (this.#serverChannel) {
|
|
287
|
+
this.removeChannel(this.#serverChannel.channelId);
|
|
288
|
+
this.#serverChannel = void 0;
|
|
289
|
+
}
|
|
290
|
+
break;
|
|
291
|
+
case "start-reconnect-timer":
|
|
292
|
+
this.#reconnectTimer = setTimeout(() => {
|
|
293
|
+
this.#reconnectTimer = void 0;
|
|
294
|
+
dispatch({ type: "reconnect-timer-fired" });
|
|
295
|
+
}, effect.delayMs);
|
|
296
|
+
break;
|
|
297
|
+
case "cancel-reconnect-timer":
|
|
298
|
+
if (this.#reconnectTimer !== void 0) {
|
|
299
|
+
clearTimeout(this.#reconnectTimer);
|
|
300
|
+
this.#reconnectTimer = void 0;
|
|
301
|
+
}
|
|
302
|
+
break;
|
|
303
|
+
case "start-keepalive":
|
|
304
|
+
this.#startKeepalive();
|
|
305
|
+
break;
|
|
306
|
+
case "stop-keepalive":
|
|
307
|
+
this.#stopKeepalive();
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Create a WebSocket and wire up event handlers to dispatch messages.
|
|
313
|
+
*
|
|
314
|
+
* The message handler is set up IMMEDIATELY after creation (before
|
|
315
|
+
* the open event) to handle the race condition where the server sends
|
|
316
|
+
* "ready" before the client's open promise resolves.
|
|
317
|
+
*/
|
|
318
|
+
#doCreateWebsocket(dispatch) {
|
|
319
|
+
const peerId = this.#peerId;
|
|
320
|
+
if (!peerId) {
|
|
321
|
+
dispatch({
|
|
322
|
+
type: "socket-error",
|
|
323
|
+
error: /* @__PURE__ */ new Error("Cannot connect: peerId not set")
|
|
324
|
+
});
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const url = typeof this.#options.url === "function" ? this.#options.url(peerId) : this.#options.url;
|
|
328
|
+
try {
|
|
329
|
+
if (this.#options.headers && Object.keys(this.#options.headers).length > 0) this.#socket = new this.#WebSocketImpl(url, { headers: this.#options.headers });
|
|
330
|
+
else this.#socket = new this.#WebSocketImpl(url);
|
|
331
|
+
this.#socket.binaryType = "arraybuffer";
|
|
332
|
+
const socket = this.#socket;
|
|
333
|
+
socket.addEventListener("message", (event) => {
|
|
334
|
+
this.#handleMessage(event, dispatch);
|
|
335
|
+
});
|
|
336
|
+
let settled = false;
|
|
337
|
+
const onOpen = () => {
|
|
338
|
+
cleanup();
|
|
339
|
+
settled = true;
|
|
340
|
+
dispatch({ type: "socket-opened" });
|
|
341
|
+
socket.addEventListener("close", (event) => {
|
|
342
|
+
dispatch({
|
|
343
|
+
type: "socket-closed",
|
|
344
|
+
code: event.code,
|
|
345
|
+
reason: event.reason
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
};
|
|
349
|
+
const onError = () => {
|
|
350
|
+
if (settled) return;
|
|
351
|
+
cleanup();
|
|
352
|
+
settled = true;
|
|
353
|
+
dispatch({
|
|
354
|
+
type: "socket-error",
|
|
355
|
+
error: /* @__PURE__ */ new Error("WebSocket connection failed")
|
|
356
|
+
});
|
|
357
|
+
};
|
|
358
|
+
const onClose = () => {
|
|
359
|
+
if (settled) return;
|
|
360
|
+
cleanup();
|
|
361
|
+
settled = true;
|
|
362
|
+
dispatch({
|
|
363
|
+
type: "socket-error",
|
|
364
|
+
error: /* @__PURE__ */ new Error("WebSocket closed during connection")
|
|
365
|
+
});
|
|
366
|
+
};
|
|
367
|
+
const cleanup = () => {
|
|
368
|
+
socket.removeEventListener("open", onOpen);
|
|
369
|
+
socket.removeEventListener("error", onError);
|
|
370
|
+
socket.removeEventListener("close", onClose);
|
|
371
|
+
};
|
|
372
|
+
socket.addEventListener("open", onOpen);
|
|
373
|
+
socket.addEventListener("error", onError);
|
|
374
|
+
socket.addEventListener("close", onClose);
|
|
375
|
+
} catch (error) {
|
|
376
|
+
dispatch({
|
|
377
|
+
type: "socket-error",
|
|
378
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Handle incoming Websocket messages.
|
|
384
|
+
*
|
|
385
|
+
* Text frames carry the "ready" handshake and keepalive pong.
|
|
386
|
+
* Binary frames carry CBOR-encoded ChannelMsg.
|
|
387
|
+
*/
|
|
388
|
+
#handleMessage(event, dispatch) {
|
|
389
|
+
const data = event.data;
|
|
390
|
+
if (typeof data === "string") {
|
|
391
|
+
if (data === "ready") dispatch({ type: "server-ready" });
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (data instanceof ArrayBuffer) try {
|
|
395
|
+
const wires = decodeBinaryWires(new Uint8Array(data), this.#reassembler);
|
|
396
|
+
if (!wires) return;
|
|
397
|
+
for (const wire of wires) {
|
|
398
|
+
const result = applyInboundAliasing(this.#aliasState, wire);
|
|
399
|
+
this.#aliasState = result.state;
|
|
400
|
+
if (result.error || !result.msg) {
|
|
401
|
+
console.warn("[WebsocketClient] alias resolution failed:", result.error);
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
this.#handleChannelMessage(result.msg);
|
|
405
|
+
}
|
|
406
|
+
} catch (error) {
|
|
407
|
+
console.error("Failed to decode message:", error);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Handle a decoded channel message.
|
|
412
|
+
*/
|
|
413
|
+
#handleChannelMessage(msg) {
|
|
414
|
+
if (!this.#serverChannel) return;
|
|
415
|
+
this.#serverChannel.onReceive(msg);
|
|
416
|
+
}
|
|
417
|
+
#startKeepalive() {
|
|
418
|
+
this.#stopKeepalive();
|
|
419
|
+
const interval = this.#options.keepaliveInterval ?? 3e4;
|
|
420
|
+
this.#keepaliveTimer = setInterval(() => {
|
|
421
|
+
if (this.#socket?.readyState === READY_STATE.OPEN) this.#socket.send("ping");
|
|
422
|
+
}, interval);
|
|
423
|
+
}
|
|
424
|
+
#stopKeepalive() {
|
|
425
|
+
if (this.#keepaliveTimer) {
|
|
426
|
+
clearInterval(this.#keepaliveTimer);
|
|
427
|
+
this.#keepaliveTimer = void 0;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
#setupLifecycleEvents() {
|
|
431
|
+
let wasConnectedBefore = false;
|
|
432
|
+
this.#handle.subscribeToTransitions((transition) => {
|
|
433
|
+
this.#options.lifecycle?.onStateChange?.(transition);
|
|
434
|
+
const { from, to } = transition;
|
|
435
|
+
if (to.status === "disconnected" && to.reason) this.#options.lifecycle?.onDisconnect?.(to.reason);
|
|
436
|
+
if (to.status === "reconnecting") this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs);
|
|
437
|
+
if (wasConnectedBefore && (from.status === "reconnecting" || from.status === "connecting") && (to.status === "connected" || to.status === "ready")) this.#options.lifecycle?.onReconnected?.();
|
|
438
|
+
if (to.status === "ready") {
|
|
439
|
+
this.#options.lifecycle?.onReady?.();
|
|
440
|
+
wasConnectedBefore = true;
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Get the current connection state.
|
|
446
|
+
*/
|
|
447
|
+
getState() {
|
|
448
|
+
return this.#handle.getState();
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Subscribe to state transitions.
|
|
452
|
+
*/
|
|
453
|
+
subscribeToTransitions(listener) {
|
|
454
|
+
return this.#handle.subscribeToTransitions(listener);
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Wait for a specific state.
|
|
458
|
+
*/
|
|
459
|
+
waitForState(predicate, options) {
|
|
460
|
+
return this.#handle.waitForState(predicate, options);
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Wait for a specific status.
|
|
464
|
+
*/
|
|
465
|
+
waitForStatus(status, options) {
|
|
466
|
+
return this.#handle.waitForStatus(status, options);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Whether the client is ready (server ready signal received).
|
|
470
|
+
*/
|
|
471
|
+
get isReady() {
|
|
472
|
+
return this.#handle.getState().status === "ready";
|
|
473
|
+
}
|
|
474
|
+
generate() {
|
|
475
|
+
const nextFrameId = createFrameIdCounter();
|
|
476
|
+
this.#aliasState = emptyAliasState();
|
|
477
|
+
return {
|
|
478
|
+
transportType: this.transportType,
|
|
479
|
+
send: (msg) => {
|
|
480
|
+
const socket = this.#socket;
|
|
481
|
+
if (!socket || socket.readyState !== READY_STATE.OPEN) return;
|
|
482
|
+
const { state, wire } = applyOutboundAliasing(this.#aliasState, msg);
|
|
483
|
+
this.#aliasState = state;
|
|
484
|
+
encodeWireFrameAndSend(wire, (data) => socket.send(new Uint8Array(data).buffer), this.#fragmentThreshold, nextFrameId);
|
|
485
|
+
},
|
|
486
|
+
stop: () => {}
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
async onStart() {
|
|
490
|
+
if (!this.identity) throw new Error("Transport not properly initialized — identity not available");
|
|
491
|
+
this.#peerId = this.identity.peerId;
|
|
492
|
+
this.#handle.dispatch({ type: "start" });
|
|
493
|
+
}
|
|
494
|
+
async onStop() {
|
|
495
|
+
this.#reassembler.dispose();
|
|
496
|
+
this.#handle.dispatch({ type: "stop" });
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
/**
|
|
500
|
+
* Create a Websocket client transport factory for browser-to-server
|
|
501
|
+
* connections.
|
|
502
|
+
*
|
|
503
|
+
* Returns an `TransportFactory` — a closure that creates a fresh transport
|
|
504
|
+
* instance when called. Pass directly to `Exchange({ transports: [...] })`.
|
|
505
|
+
*
|
|
506
|
+
* @example
|
|
507
|
+
* ```typescript
|
|
508
|
+
* import { createWebsocketClient } from "@kyneta/websocket-transport/browser"
|
|
509
|
+
*
|
|
510
|
+
* const exchange = new Exchange({
|
|
511
|
+
* transports: [createWebsocketClient({
|
|
512
|
+
* url: "ws://localhost:3000/ws",
|
|
513
|
+
* WebSocket,
|
|
514
|
+
* reconnect: { enabled: true },
|
|
515
|
+
* })],
|
|
516
|
+
* })
|
|
517
|
+
* ```
|
|
518
|
+
*/
|
|
519
|
+
function createWebsocketClient(options) {
|
|
520
|
+
return () => new WebsocketClientTransport(options);
|
|
521
|
+
}
|
|
522
|
+
//#endregion
|
|
523
|
+
export { wrapNodeWebsocket as a, READY_STATE as i, WebsocketClientTransport as n, wrapStandardWebsocket as o, createWebsocketClient as r, createWsClientProgram as s, DEFAULT_FRAGMENT_THRESHOLD as t };
|
|
524
|
+
|
|
525
|
+
//# sourceMappingURL=client-transport-B2V7s2VP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-transport-B2V7s2VP.js","names":["#fragmentThreshold","#reassembler","#options","#WebSocketImpl","#handle","#executeEffect","#setupLifecycleEvents","#doCreateWebsocket","#socket","#serverChannel","#reconnectTimer","#startKeepalive","#stopKeepalive","#peerId","#handleMessage","#aliasState","#handleChannelMessage","#keepaliveTimer"],"sources":["../src/client-program.ts","../src/types.ts","../src/client-transport.ts"],"sourcesContent":["// client-program — pure Mealy machine for websocket client connection lifecycle.\n//\n// The client program encodes every state transition and effect as data.\n// The imperative shell (client-transport.ts) interprets effects as I/O.\n// Tests assert on data — no sockets, no timing, never flaky.\n//\n// Algebra: Program<WsClientMsg, WebsocketClientState, WsClientEffect>\n// Interpreter: client-transport.ts executeClientEffect()\n//\n// The websocket client has a 5-state lifecycle with an extra \"ready\" state\n// compared to the unix socket client. The server sends a text \"ready\" signal\n// after the connection opens, and only then does the client create a channel\n// and start the establishment handshake.\n//\n// Race condition: the server may send \"ready\" before the client's open event\n// fires (server-ready while connecting). The program handles this by\n// transitioning directly to ready, skipping the connected state.\n\nimport type { Program } from \"@kyneta/machine\"\nimport type { ReconnectOptions } from \"@kyneta/transport\"\nimport { computeBackoffDelay, DEFAULT_RECONNECT } from \"@kyneta/transport\"\n\nimport type { DisconnectReason, WebsocketClientState } from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\nexport type WsClientMsg =\n | { type: \"start\" }\n | { type: \"socket-opened\" }\n | { type: \"server-ready\" }\n | { type: \"socket-closed\"; code: number; reason: string }\n | { type: \"socket-error\"; error: Error }\n | { type: \"reconnect-timer-fired\" }\n | { type: \"stop\" }\n\n// ---------------------------------------------------------------------------\n// Effects (data — interpreted by the imperative shell)\n// ---------------------------------------------------------------------------\n\nexport type WsClientEffect =\n | { type: \"create-websocket\"; attempt: number }\n | { type: \"close-websocket\" }\n | { type: \"add-channel-and-establish\" }\n | { type: \"remove-channel\" }\n | { type: \"start-reconnect-timer\"; delayMs: number }\n | { type: \"cancel-reconnect-timer\" }\n | { type: \"start-keepalive\" }\n | { type: \"stop-keepalive\" }\n\n// ---------------------------------------------------------------------------\n// Program factory\n// ---------------------------------------------------------------------------\n\nexport interface WsClientProgramOptions {\n reconnect?: Partial<ReconnectOptions>\n /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */\n jitterFn?: () => number\n}\n\n/**\n * Create the websocket client connection lifecycle program — a pure Mealy machine.\n *\n * The returned `Program<WsClientMsg, WebsocketClientState, WsClientEffect>`\n * encodes every state transition and effect as inspectable data. The imperative\n * shell interprets `WsClientEffect` as actual I/O.\n */\nexport function createWsClientProgram(\n options: WsClientProgramOptions = {},\n): Program<WsClientMsg, WebsocketClientState, WsClientEffect> {\n const { jitterFn = () => Math.random() * 1000 } = options\n const reconnect: ReconnectOptions = {\n ...DEFAULT_RECONNECT,\n ...options.reconnect,\n }\n\n /**\n * Attempt to transition into reconnecting, or give up and disconnect.\n *\n * Pure — computes the next state and effects from the current attempt\n * count and reconnect configuration. Returns a tuple suitable for\n * spreading into an `update` return.\n */\n function tryReconnect(\n currentAttempt: number,\n reason: DisconnectReason,\n ...extraEffects: WsClientEffect[]\n ): [WebsocketClientState, ...WsClientEffect[]] {\n if (!reconnect.enabled) {\n return [{ status: \"disconnected\", reason }, ...extraEffects]\n }\n\n if (currentAttempt >= reconnect.maxAttempts) {\n return [\n {\n status: \"disconnected\",\n reason: { type: \"max-retries-exceeded\", attempts: currentAttempt },\n },\n ...extraEffects,\n ]\n }\n\n const delay = computeBackoffDelay(\n currentAttempt + 1,\n reconnect.baseDelay,\n reconnect.maxDelay,\n jitterFn(),\n )\n\n return [\n {\n status: \"reconnecting\",\n attempt: currentAttempt + 1,\n nextAttemptMs: delay,\n },\n ...extraEffects,\n { type: \"start-reconnect-timer\", delayMs: delay },\n ]\n }\n\n return {\n init: [{ status: \"disconnected\" }],\n\n update(msg, model): [WebsocketClientState, ...WsClientEffect[]] {\n switch (msg.type) {\n // -----------------------------------------------------------------\n // start\n // -----------------------------------------------------------------\n case \"start\": {\n if (model.status !== \"disconnected\") return [model]\n return [\n { status: \"connecting\", attempt: 1 },\n { type: \"create-websocket\", attempt: 1 },\n ]\n }\n\n // -----------------------------------------------------------------\n // socket-opened\n // -----------------------------------------------------------------\n case \"socket-opened\": {\n if (model.status !== \"connecting\") return [model]\n return [{ status: \"connected\" }, { type: \"start-keepalive\" }]\n }\n\n // -----------------------------------------------------------------\n // server-ready\n // -----------------------------------------------------------------\n case \"server-ready\": {\n // Already ready — ignore duplicate\n if (model.status === \"ready\") return [model]\n\n // Normal path: connected → ready\n if (model.status === \"connected\") {\n return [{ status: \"ready\" }, { type: \"add-channel-and-establish\" }]\n }\n\n // Race condition: server sent \"ready\" before client's open event fired.\n // Skip connected, go directly to ready with both keepalive and channel effects.\n if (model.status === \"connecting\") {\n return [\n { status: \"ready\" },\n { type: \"start-keepalive\" },\n { type: \"add-channel-and-establish\" },\n ]\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // socket-closed\n // -----------------------------------------------------------------\n case \"socket-closed\": {\n const reason: DisconnectReason = {\n type: \"closed\",\n code: msg.code,\n reason: msg.reason,\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(0, reason, { type: \"stop-keepalive\" })\n }\n\n if (model.status === \"ready\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"stop-keepalive\" },\n { type: \"remove-channel\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // socket-error\n // -----------------------------------------------------------------\n case \"socket-error\": {\n const reason: DisconnectReason = {\n type: \"error\",\n error: msg.error,\n }\n\n if (model.status === \"connecting\") {\n return tryReconnect(model.attempt, reason)\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(0, reason, { type: \"stop-keepalive\" })\n }\n\n if (model.status === \"ready\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"stop-keepalive\" },\n { type: \"remove-channel\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // reconnect-timer-fired\n // -----------------------------------------------------------------\n case \"reconnect-timer-fired\": {\n if (model.status !== \"reconnecting\") return [model]\n return [\n { status: \"connecting\", attempt: model.attempt },\n { type: \"create-websocket\", attempt: model.attempt },\n ]\n }\n\n // -----------------------------------------------------------------\n // stop\n // -----------------------------------------------------------------\n case \"stop\": {\n if (model.status === \"disconnected\") return [model]\n\n const effects: WsClientEffect[] = [{ type: \"cancel-reconnect-timer\" }]\n\n if (model.status === \"connecting\") {\n effects.push({ type: \"close-websocket\" })\n }\n\n if (model.status === \"connected\") {\n effects.push(\n { type: \"close-websocket\" },\n { type: \"stop-keepalive\" },\n )\n }\n\n if (model.status === \"ready\") {\n effects.push(\n { type: \"close-websocket\" },\n { type: \"stop-keepalive\" },\n { type: \"remove-channel\" },\n )\n }\n\n return [\n { status: \"disconnected\", reason: { type: \"intentional\" } },\n ...effects,\n ]\n }\n }\n },\n }\n}\n","// types — framework-agnostic Websocket abstractions for @kyneta/websocket-transport.\n//\n// The `Socket` interface decouples the adapter from any specific Websocket\n// library (browser WebSocket, Node `ws`, Bun ServerWebSocket). Platform-\n// specific wrappers (`wrapStandardWebsocket`, `wrapNodeWebsocket`,\n// `wrapBunWebsocket`) adapt concrete implementations to this interface.\n//\n// Ported from @loro-extended/adapter-websocket's WsSocket with kyneta\n// naming conventions applied.\n\nimport type {\n TransitionListener as GenericTransitionListener,\n PeerId,\n StateTransition,\n} from \"@kyneta/transport\"\n\n// ---------------------------------------------------------------------------\n// WebSocket readyState constants (spec values, no global dependency)\n// ---------------------------------------------------------------------------\n\n/**\n * WebSocket readyState constants per the WHATWG WebSocket spec.\n * Replaces references to `WebSocket.CONNECTING`, `WebSocket.OPEN`, etc.\n * so that shared code never depends on the browser global.\n */\nexport const READY_STATE = {\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3,\n} as const\n\n// ---------------------------------------------------------------------------\n// Structural event types (replace DOM MessageEvent / CloseEvent)\n// ---------------------------------------------------------------------------\n\n/** Minimal message event — only the fields the transport accesses. */\nexport interface WebSocketMessageEvent {\n readonly data: string | ArrayBuffer\n}\n\n/** Minimal close event — only the fields the transport accesses. */\nexport interface WebSocketCloseEvent {\n readonly code: number\n readonly reason: string\n}\n\n// ---------------------------------------------------------------------------\n// WebSocket instance and constructor structural types\n// ---------------------------------------------------------------------------\n\n/**\n * Structural type for a constructed WebSocket instance.\n *\n * Covers the browser's `WebSocket`, the `ws` library's `WebSocket`,\n * and Bun's client `WebSocket` — all satisfy this interface without casting.\n *\n * The client transport uses `addEventListener`/`removeEventListener` for\n * one-shot connection handlers with explicit cleanup during the connect\n * phase. This is why `WebSocketLike` exists alongside the server-side\n * `Socket` interface (which uses single-callback registration).\n */\nexport interface WebSocketLike {\n readonly readyState: number\n binaryType: string\n send(data: string | ArrayBuffer): void\n close(code?: number, reason?: string): void\n addEventListener(type: string, listener: (event: any) => void): void\n removeEventListener(type: string, listener: (event: any) => void): void\n}\n\n/**\n * Structural type for a WebSocket constructor.\n *\n * Type safety for constructor arguments is intentionally at the options\n * layer (`WebsocketClientOptions.headers`), not here. The `...rest: any[]`\n * absorbs both the browser's `protocols` arg and backend's `{ headers }`\n * arg without requiring the transport to know which runtime it's in.\n */\nexport type WebSocketConstructor = new (\n url: string,\n ...rest: any[]\n) => WebSocketLike\n\n// ---------------------------------------------------------------------------\n// Socket ready states (string enum for server-side Socket interface)\n// ---------------------------------------------------------------------------\n\n/**\n * Websocket ready states — mirrors the standard WebSocket readyState\n * values as human-readable strings.\n */\nexport type SocketReadyState = \"connecting\" | \"open\" | \"closing\" | \"closed\"\n\n// ---------------------------------------------------------------------------\n// Socket interface\n// ---------------------------------------------------------------------------\n\n/**\n * Framework-agnostic Websocket interface.\n *\n * This allows the adapter to work with any Websocket library:\n * - Browser `WebSocket` via `wrapStandardWebsocket()`\n * - Node.js `ws` library via `wrapNodeWebsocket()`\n * - Bun `ServerWebSocket` via `wrapBunWebsocket()`\n *\n * The interface is intentionally minimal — only the operations the\n * adapter needs are exposed.\n */\nexport interface Socket {\n /**\n * Narrowed to `Uint8Array<ArrayBuffer>` because the strictest downstream\n * runtimes reject `SharedArrayBuffer`-backed views: Bun's `BufferSource`\n * resolves to `ArrayBufferView<ArrayBuffer> | ArrayBuffer`, and Hono's\n * `WSContext.send` takes `Uint8Array<ArrayBuffer>` directly. The wire\n * pipeline allocates with `new Uint8Array(n)`, so producers satisfy this\n * without changes.\n */\n send(data: Uint8Array<ArrayBuffer> | string): void\n\n /** Close the Websocket connection. */\n close(code?: number, reason?: string): void\n\n /** Register a handler for incoming messages (binary or text). */\n onMessage(handler: (data: Uint8Array<ArrayBuffer> | string) => void): void\n\n /** Register a handler for connection close. */\n onClose(handler: (code: number, reason: string) => void): void\n\n /** Register a handler for errors. */\n onError(handler: (error: Error) => void): void\n\n /** The current ready state of the Websocket. */\n readonly readyState: SocketReadyState\n}\n\n// ---------------------------------------------------------------------------\n// Connection types — used by server adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Options for handling a new Websocket connection on the server.\n */\nexport interface WebsocketConnectionOptions {\n /** The Websocket instance, wrapped in the Socket interface. */\n socket: Socket\n\n /** Optional peer ID extracted from the upgrade request. */\n peerId?: PeerId\n\n /** Optional authentication token from the upgrade request. */\n authToken?: string\n}\n\n/**\n * Handle for an active Websocket connection.\n */\nexport interface WebsocketConnectionHandle {\n /** The peer ID for this connection. */\n readonly peerId: PeerId\n\n /** The channel ID for this connection. */\n readonly channelId: number\n\n /** Close the connection. */\n close(code?: number, reason?: string): void\n}\n\n/**\n * Result of handling a Websocket connection on the server.\n */\nexport interface WebsocketConnectionResult {\n /** The connection handle for managing this peer. */\n connection: WebsocketConnectionHandle\n\n /** Call this to start processing messages. */\n start(): void\n}\n\n// ---------------------------------------------------------------------------\n// Disconnect reason\n// ---------------------------------------------------------------------------\n\n/**\n * Discriminated union describing why a Websocket connection was lost.\n */\nexport type DisconnectReason =\n | { type: \"intentional\" }\n | { type: \"error\"; error: Error }\n | { type: \"closed\"; code: number; reason: string }\n | { type: \"max-retries-exceeded\"; attempts: number }\n | { type: \"not-started\" }\n\n// ---------------------------------------------------------------------------\n// Connection state (for client adapter observability)\n// ---------------------------------------------------------------------------\n\n/**\n * All possible states of the Websocket client.\n *\n * State machine transitions:\n * ```\n * disconnected → connecting → connected → ready\n * ↓ ↓ ↓\n * reconnecting ← ─ ┴ ─ ─ ─ ─ ┘\n * ↓\n * connecting (retry)\n * ↓\n * disconnected (max retries)\n * ```\n */\nexport type WebsocketClientState =\n | { status: \"disconnected\"; reason?: DisconnectReason }\n | { status: \"connecting\"; attempt: number }\n | { status: \"connected\" }\n | { status: \"ready\" }\n | { status: \"reconnecting\"; attempt: number; nextAttemptMs: number }\n\n/**\n * A state transition event for websocket client states.\n * Specialized from the generic `StateTransition<S>`.\n */\nexport type WebsocketClientStateTransition =\n StateTransition<WebsocketClientState>\n\n/**\n * Listener for websocket client state transitions.\n * Specialized from the generic `TransitionListener<S>`.\n */\nexport type TransitionListener = GenericTransitionListener<WebsocketClientState>\n\n// ---------------------------------------------------------------------------\n// Socket wrapper — standard WebSocket API (browser + Node ws)\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap a standard `WebSocket` (browser or Node.js `ws` via `ws` package\n * in `WebSocket`-compatible mode) into the `Socket` interface.\n *\n * Handles `ArrayBuffer`, `Blob`, and string messages.\n */\nexport function wrapStandardWebsocket(ws: WebSocket): Socket {\n return {\n send(data: Uint8Array<ArrayBuffer> | string): void {\n ws.send(data)\n },\n\n close(code?: number, reason?: string): void {\n ws.close(code, reason)\n },\n\n onMessage(handler: (data: Uint8Array<ArrayBuffer> | string) => void): void {\n ws.addEventListener(\"message\", event => {\n if (event.data instanceof ArrayBuffer) {\n handler(new Uint8Array(event.data))\n } else if (typeof Blob !== \"undefined\" && event.data instanceof Blob) {\n // Handle Blob data (browser)\n event.data.arrayBuffer().then(buffer => {\n handler(new Uint8Array(buffer))\n })\n } else {\n handler(event.data as string)\n }\n })\n },\n\n onClose(handler: (code: number, reason: string) => void): void {\n ws.addEventListener(\"close\", event => {\n handler(event.code, event.reason)\n })\n },\n\n onError(handler: (error: Error) => void): void {\n ws.addEventListener(\"error\", _event => {\n handler(new Error(\"WebSocket error\"))\n })\n },\n\n get readyState(): SocketReadyState {\n switch (ws.readyState) {\n case READY_STATE.CONNECTING:\n return \"connecting\"\n case READY_STATE.OPEN:\n return \"open\"\n case READY_STATE.CLOSING:\n return \"closing\"\n case READY_STATE.CLOSED:\n return \"closed\"\n default:\n return \"closed\"\n }\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Socket wrapper — Node.js `ws` library (raw API, not WebSocket-compat)\n// ---------------------------------------------------------------------------\n\n/**\n * The minimal interface we need from the Node.js `ws` library's `WebSocket`.\n *\n * Using a structural type rather than importing `ws` — consumers provide\n * the actual `ws` instance, we just need these methods.\n */\nexport interface NodeWebsocketLike {\n send(data: Uint8Array<ArrayBuffer> | string): void\n close(code?: number, reason?: string): void\n on(\n event: \"message\",\n handler: (data: Buffer | ArrayBuffer | string, isBinary: boolean) => void,\n ): void\n on(event: \"close\", handler: (code: number, reason: Buffer) => void): void\n on(event: \"error\", handler: (error: Error) => void): void\n readyState: number\n}\n\n/**\n * Wrap a Node.js `ws` library WebSocket into the `Socket` interface.\n *\n * Handles `Buffer` → `Uint8Array` conversion for binary messages.\n */\nexport function wrapNodeWebsocket(ws: NodeWebsocketLike): Socket {\n const CONNECTING = 0\n const OPEN = 1\n const CLOSING = 2\n\n return {\n send(data: Uint8Array<ArrayBuffer> | string): void {\n ws.send(data)\n },\n\n close(code?: number, reason?: string): void {\n ws.close(code, reason)\n },\n\n onMessage(handler: (data: Uint8Array<ArrayBuffer> | string) => void): void {\n ws.on(\n \"message\",\n (data: Buffer | ArrayBuffer | string, isBinary: boolean) => {\n if (isBinary) {\n if (data instanceof ArrayBuffer) {\n handler(new Uint8Array(data))\n } else if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n handler(new Uint8Array(data))\n } else {\n handler(new Uint8Array(data as unknown as ArrayBuffer))\n }\n } else {\n if (typeof Buffer !== \"undefined\" && Buffer.isBuffer(data)) {\n handler(data.toString(\"utf-8\"))\n } else {\n handler(data as string)\n }\n }\n },\n )\n },\n\n onClose(handler: (code: number, reason: string) => void): void {\n ws.on(\"close\", (code: number, reason: Buffer) => {\n handler(code, reason.toString())\n })\n },\n\n onError(handler: (error: Error) => void): void {\n ws.on(\"error\", handler)\n },\n\n get readyState(): SocketReadyState {\n switch (ws.readyState) {\n case CONNECTING:\n return \"connecting\"\n case OPEN:\n return \"open\"\n case CLOSING:\n return \"closing\"\n default:\n return \"closed\"\n }\n },\n }\n}\n","// client-transport — Websocket client transport for @kyneta/exchange.\n//\n// Thin imperative shell around the pure client program (client-program.ts).\n// The program produces data effects; this module interprets them as I/O.\n//\n// FC/IS design:\n// - client-program.ts: pure Mealy machine (functional core)\n// - client-transport.ts: effect executor (imperative shell)\n//\n// Uses the kyneta wire format (CBOR codec + framing + fragmentation)\n// for binary messages. Text frames carry the \"ready\" handshake and\n// keepalive ping/pong.\n\nimport type { ObservableHandle, TransitionListener } from \"@kyneta/machine\"\nimport { createObservableProgram } from \"@kyneta/machine\"\nimport type {\n Channel,\n ChannelMsg,\n GeneratedChannel,\n PeerId,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n type AliasState,\n applyInboundAliasing,\n applyOutboundAliasing,\n createFrameIdCounter,\n decodeBinaryWires,\n emptyAliasState,\n encodeWireFrameAndSend,\n FragmentReassembler,\n} from \"@kyneta/wire\"\nimport {\n createWsClientProgram,\n type WsClientEffect,\n type WsClientMsg,\n} from \"./client-program.js\"\nimport type {\n DisconnectReason,\n WebsocketClientState,\n WebsocketClientStateTransition,\n} from \"./types.js\"\nimport {\n READY_STATE,\n type WebSocketCloseEvent,\n type WebSocketConstructor,\n type WebSocketLike,\n type WebSocketMessageEvent,\n} from \"./types.js\"\n\n// Re-export state types for convenience\nexport type {\n DisconnectReason,\n WebsocketClientState,\n WebsocketClientStateTransition,\n}\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in bytes.\n * AWS API Gateway has a 128KB limit, so 100KB provides a safe margin.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 100 * 1024\n\n/**\n * Options for the Websocket client transport (browser connections).\n */\nexport interface WebsocketClientOptions {\n /** Websocket URL to connect to. Can be a string or a function of peerId. */\n url: string | ((peerId: PeerId) => string)\n\n /**\n * WebSocket constructor — caller must provide explicitly.\n *\n * In browsers, pass the global `WebSocket`. In Node.js, pass `ws`'s\n * `WebSocket`. In Bun, pass `globalThis.WebSocket`. The transport\n * never probes `globalThis` on its own.\n */\n WebSocket: WebSocketConstructor\n\n /**\n * Headers to send during Websocket upgrade.\n * Used for authentication in service-to-service communication.\n *\n * Note: Headers are a Bun/Node-specific extension. The browser WebSocket\n * API does not support custom headers per the WHATWG spec.\n */\n headers?: Record<string, string>\n\n /** Reconnection options. */\n reconnect?: {\n enabled?: boolean\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** Keepalive interval in ms (default: 30000). */\n keepaliveInterval?: number\n\n /**\n * Fragment threshold in bytes. Messages larger than this are fragmented.\n * Set to 0 to disable fragmentation (not recommended for cloud deployments).\n * Default: 100KB\n */\n fragmentThreshold?: number\n\n /** Lifecycle event callbacks. */\n lifecycle?: WebsocketClientLifecycleEvents\n}\n\n/**\n * Lifecycle event callbacks for the Websocket client.\n */\nexport interface WebsocketClientLifecycleEvents {\n /** Called on every state transition (delivered async via microtask). */\n onStateChange?: (transition: WebsocketClientStateTransition) => void\n\n /** Called when the connection is lost. */\n onDisconnect?: (reason: DisconnectReason) => void\n\n /** Called when a reconnection attempt is scheduled. */\n onReconnecting?: (attempt: number, nextAttemptMs: number) => void\n\n /** Called when reconnection succeeds after a previous connection. */\n onReconnected?: () => void\n\n /** Called when the server sends the \"ready\" signal. */\n onReady?: () => void\n}\n\n// ---------------------------------------------------------------------------\n// WebsocketClientTransport\n// ---------------------------------------------------------------------------\n\n/**\n * Websocket client network transport for @kyneta/exchange.\n *\n * Connects to a Websocket server, sends and receives ChannelMsg via\n * the kyneta wire format (CBOR codec + framing + fragmentation).\n *\n * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —\n * a pure Mealy machine whose transitions are deterministically testable.\n * This class is the imperative shell that interprets data effects as I/O.\n *\n * Prefer the factory functions for construction:\n * - `createWebsocketClient()` — browser-to-server (from `./browser`)\n * - `createServiceWebsocketClient()` — service-to-service with headers (from `./server`)\n */\nexport class WebsocketClientTransport extends Transport<void> {\n #peerId?: PeerId\n #options: WebsocketClientOptions\n #WebSocketImpl: WebSocketConstructor\n\n // Observable program handle — created in constructor, drives all state\n #handle: ObservableHandle<WsClientMsg, WebsocketClientState>\n\n // Executor-local I/O state — not in the program model\n #socket?: WebSocketLike\n #serverChannel?: Channel\n #keepaliveTimer?: ReturnType<typeof setInterval>\n #reconnectTimer?: ReturnType<typeof setTimeout>\n\n // Fragmentation\n readonly #fragmentThreshold: number\n readonly #reassembler: FragmentReassembler\n\n // Per-channel alias state (Phase 4). Single channel per client.\n #aliasState: AliasState = emptyAliasState()\n\n constructor(options: WebsocketClientOptions) {\n super({ transportType: \"websocket-client\" })\n this.#options = options\n this.#WebSocketImpl = options.WebSocket\n this.#fragmentThreshold =\n options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new FragmentReassembler({\n timeoutMs: 10_000,\n })\n\n const program = createWsClientProgram({\n reconnect: options.reconnect,\n })\n\n this.#handle = createObservableProgram(program, (effect, dispatch) => {\n this.#executeEffect(effect, dispatch)\n })\n\n // Set up lifecycle event forwarding\n this.#setupLifecycleEvents()\n }\n\n // ==========================================================================\n // Effect executor — interprets data effects as I/O\n // ==========================================================================\n\n #executeEffect(\n effect: WsClientEffect,\n dispatch: (msg: WsClientMsg) => void,\n ): void {\n switch (effect.type) {\n case \"create-websocket\": {\n this.#doCreateWebsocket(dispatch)\n break\n }\n\n case \"close-websocket\": {\n if (this.#socket) {\n this.#socket.close(1000, \"Client disconnecting\")\n this.#socket = undefined\n }\n break\n }\n\n case \"add-channel-and-establish\": {\n // Clean up previous channel if it exists (e.g. after reconnect)\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n\n // Fresh reassembler for the new connection — stale fragments from\n // the old connection must not collide with new fragments.\n this.#reassembler.reset()\n\n this.#serverChannel = this.addChannel()\n\n // Establish immediately — the server already signaled ready\n this.establishChannel(this.#serverChannel.channelId)\n break\n }\n\n case \"remove-channel\": {\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n break\n }\n\n case \"start-reconnect-timer\": {\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = undefined\n dispatch({ type: \"reconnect-timer-fired\" })\n }, effect.delayMs)\n break\n }\n\n case \"cancel-reconnect-timer\": {\n if (this.#reconnectTimer !== undefined) {\n clearTimeout(this.#reconnectTimer)\n this.#reconnectTimer = undefined\n }\n break\n }\n\n case \"start-keepalive\": {\n this.#startKeepalive()\n break\n }\n\n case \"stop-keepalive\": {\n this.#stopKeepalive()\n break\n }\n }\n }\n\n // ==========================================================================\n // WebSocket creation — the core I/O operation\n // ==========================================================================\n\n /**\n * Create a WebSocket and wire up event handlers to dispatch messages.\n *\n * The message handler is set up IMMEDIATELY after creation (before\n * the open event) to handle the race condition where the server sends\n * \"ready\" before the client's open promise resolves.\n */\n #doCreateWebsocket(dispatch: (msg: WsClientMsg) => void): void {\n const peerId = this.#peerId\n if (!peerId) {\n dispatch({\n type: \"socket-error\",\n error: new Error(\"Cannot connect: peerId not set\"),\n })\n return\n }\n\n // Resolve URL\n const url =\n typeof this.#options.url === \"function\"\n ? this.#options.url(peerId)\n : this.#options.url\n\n try {\n // Create WebSocket — pass headers as second arg when present.\n // The structural WebSocketConstructor's `...rest: any[]` absorbs\n // both the browser's protocols arg and backend's { headers } arg.\n if (\n this.#options.headers &&\n Object.keys(this.#options.headers).length > 0\n ) {\n this.#socket = new this.#WebSocketImpl(url, {\n headers: this.#options.headers,\n })\n } else {\n this.#socket = new this.#WebSocketImpl(url)\n }\n this.#socket.binaryType = \"arraybuffer\"\n\n const socket = this.#socket\n\n // Set up message handler IMMEDIATELY to handle the \"ready\" race condition.\n // The server may send \"ready\" before the open event fires.\n socket.addEventListener(\"message\", (event: WebSocketMessageEvent) => {\n this.#handleMessage(event, dispatch)\n })\n\n // Track whether we've dispatched a terminal event for this connection attempt\n let settled = false\n\n const onOpen = () => {\n cleanup()\n settled = true\n dispatch({ type: \"socket-opened\" })\n\n // After open, set up permanent close handler for post-connection closes\n socket.addEventListener(\"close\", (event: WebSocketCloseEvent) => {\n dispatch({\n type: \"socket-closed\",\n code: event.code,\n reason: event.reason,\n })\n })\n }\n\n const onError = () => {\n if (settled) return\n cleanup()\n settled = true\n dispatch({\n type: \"socket-error\",\n error: new Error(\"WebSocket connection failed\"),\n })\n }\n\n const onClose = () => {\n if (settled) return\n cleanup()\n settled = true\n dispatch({\n type: \"socket-error\",\n error: new Error(\"WebSocket closed during connection\"),\n })\n }\n\n const cleanup = () => {\n socket.removeEventListener(\"open\", onOpen)\n socket.removeEventListener(\"error\", onError)\n socket.removeEventListener(\"close\", onClose)\n }\n\n socket.addEventListener(\"open\", onOpen)\n socket.addEventListener(\"error\", onError)\n socket.addEventListener(\"close\", onClose)\n } catch (error) {\n dispatch({\n type: \"socket-error\",\n error: error instanceof Error ? error : new Error(String(error)),\n })\n }\n }\n\n // ==========================================================================\n // Message handling — I/O parsing logic\n // ==========================================================================\n\n /**\n * Handle incoming Websocket messages.\n *\n * Text frames carry the \"ready\" handshake and keepalive pong.\n * Binary frames carry CBOR-encoded ChannelMsg.\n */\n #handleMessage(\n event: WebSocketMessageEvent,\n dispatch: (msg: WsClientMsg) => void,\n ): void {\n const data = event.data\n\n // Handle text messages (keepalive and ready signal)\n if (typeof data === \"string\") {\n if (data === \"ready\") {\n dispatch({ type: \"server-ready\" })\n }\n // Ignore pong responses and other text\n return\n }\n\n // Handle binary messages through shared decode pipeline\n if (data instanceof ArrayBuffer) {\n try {\n const wires = decodeBinaryWires(new Uint8Array(data), this.#reassembler)\n if (!wires) return\n for (const wire of wires) {\n const result = applyInboundAliasing(this.#aliasState, wire)\n this.#aliasState = result.state\n if (result.error || !result.msg) {\n console.warn(\n \"[WebsocketClient] alias resolution failed:\",\n result.error,\n )\n continue\n }\n this.#handleChannelMessage(result.msg)\n }\n } catch (error) {\n console.error(\"Failed to decode message:\", error)\n }\n }\n }\n\n /**\n * Handle a decoded channel message.\n */\n #handleChannelMessage(msg: ChannelMsg): void {\n if (!this.#serverChannel) {\n return\n }\n\n // Deliver synchronously — the Synchronizer's receive queue prevents recursion\n this.#serverChannel.onReceive(msg)\n }\n\n // ==========================================================================\n // Keepalive\n // ==========================================================================\n\n #startKeepalive(): void {\n this.#stopKeepalive()\n\n const interval = this.#options.keepaliveInterval ?? 30_000\n\n this.#keepaliveTimer = setInterval(() => {\n if (this.#socket?.readyState === READY_STATE.OPEN) {\n this.#socket.send(\"ping\")\n }\n }, interval)\n }\n\n #stopKeepalive(): void {\n if (this.#keepaliveTimer) {\n clearInterval(this.#keepaliveTimer)\n this.#keepaliveTimer = undefined\n }\n }\n\n // ==========================================================================\n // Lifecycle event forwarding\n // ==========================================================================\n\n #setupLifecycleEvents(): void {\n // wasConnectedBefore is observer-local state, not in the program model\n let wasConnectedBefore = false\n\n this.#handle.subscribeToTransitions(transition => {\n // Forward to onStateChange callback\n this.#options.lifecycle?.onStateChange?.(transition)\n\n const { from, to } = transition\n\n // onDisconnect: transitioning TO disconnected\n if (to.status === \"disconnected\" && to.reason) {\n this.#options.lifecycle?.onDisconnect?.(to.reason)\n }\n\n // onReconnecting: transitioning TO reconnecting\n if (to.status === \"reconnecting\") {\n this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs)\n }\n\n // onReconnected: from reconnecting/connecting TO connected/ready (after prior connection)\n if (\n wasConnectedBefore &&\n (from.status === \"reconnecting\" || from.status === \"connecting\") &&\n (to.status === \"connected\" || to.status === \"ready\")\n ) {\n this.#options.lifecycle?.onReconnected?.()\n }\n\n // onReady: transitioning TO ready\n if (to.status === \"ready\") {\n this.#options.lifecycle?.onReady?.()\n wasConnectedBefore = true\n }\n })\n }\n\n // ==========================================================================\n // State observation — delegated to the observable handle\n // ==========================================================================\n\n /**\n * Get the current connection state.\n */\n getState(): WebsocketClientState {\n return this.#handle.getState()\n }\n\n /**\n * Subscribe to state transitions.\n */\n subscribeToTransitions(\n listener: TransitionListener<WebsocketClientState>,\n ): () => void {\n return this.#handle.subscribeToTransitions(listener)\n }\n\n /**\n * Wait for a specific state.\n */\n waitForState(\n predicate: (state: WebsocketClientState) => boolean,\n options?: { timeoutMs?: number },\n ): Promise<WebsocketClientState> {\n return this.#handle.waitForState(predicate, options)\n }\n\n /**\n * Wait for a specific status.\n */\n waitForStatus(\n status: WebsocketClientState[\"status\"],\n options?: { timeoutMs?: number },\n ): Promise<WebsocketClientState> {\n return this.#handle.waitForStatus(status, options)\n }\n\n /**\n * Whether the client is ready (server ready signal received).\n */\n get isReady(): boolean {\n return this.#handle.getState().status === \"ready\"\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n protected generate(): GeneratedChannel {\n const nextFrameId = createFrameIdCounter()\n // New channel = fresh alias state; reset on (re)connect.\n this.#aliasState = emptyAliasState()\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n const socket = this.#socket\n if (!socket || socket.readyState !== READY_STATE.OPEN) {\n return\n }\n\n const { state, wire } = applyOutboundAliasing(this.#aliasState, msg)\n this.#aliasState = state\n\n encodeWireFrameAndSend(\n wire,\n data => socket.send(new Uint8Array(data).buffer),\n this.#fragmentThreshold,\n nextFrameId,\n )\n },\n stop: () => {\n // Don't call disconnect here — channel.stop() is called when\n // the channel is removed, which can happen during effect execution.\n // The actual disconnect is handled by onStop() or the program.\n },\n }\n }\n\n async onStart(): Promise<void> {\n if (!this.identity) {\n throw new Error(\n \"Transport not properly initialized — identity not available\",\n )\n }\n this.#peerId = this.identity.peerId\n this.#handle.dispatch({ type: \"start\" })\n }\n\n async onStop(): Promise<void> {\n this.#reassembler.dispose()\n this.#handle.dispatch({ type: \"stop\" })\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/**\n * Create a Websocket client transport factory for browser-to-server\n * connections.\n *\n * Returns an `TransportFactory` — a closure that creates a fresh transport\n * instance when called. Pass directly to `Exchange({ transports: [...] })`.\n *\n * @example\n * ```typescript\n * import { createWebsocketClient } from \"@kyneta/websocket-transport/browser\"\n *\n * const exchange = new Exchange({\n * transports: [createWebsocketClient({\n * url: \"ws://localhost:3000/ws\",\n * WebSocket,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createWebsocketClient(\n options: WebsocketClientOptions,\n): TransportFactory {\n return () => new WebsocketClientTransport(options)\n}\n"],"mappings":";;;;;;;;;;;AAoEA,SAAgB,sBACd,UAAkC,EAAE,EACwB;CAC5D,MAAM,EAAE,iBAAiB,KAAK,QAAQ,GAAG,QAAS;CAClD,MAAM,YAA8B;EAClC,GAAG;EACH,GAAG,QAAQ;EACZ;;;;;;;;CAS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