@lushly-dev/afd-client 0.1.0 → 0.3.1
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/LICENSE +21 -26
- package/README.md +297 -240
- package/dist/client.d.ts +30 -4
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +139 -10
- package/dist/client.js.map +1 -1
- package/dist/direct.d.ts +210 -11
- package/dist/direct.d.ts.map +1 -1
- package/dist/direct.js +439 -17
- package/dist/direct.js.map +1 -1
- package/dist/handlers.d.ts +59 -0
- package/dist/handlers.d.ts.map +1 -0
- package/dist/handlers.js +332 -0
- package/dist/handlers.js.map +1 -0
- package/dist/handoff.d.ts +335 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +419 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -2
- package/dist/index.js.map +1 -1
- package/dist/transport.d.ts +3 -4
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +3 -4
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +8 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +12 -3
package/dist/handlers.js
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Built-in protocol handlers for WebSocket and SSE
|
|
3
|
+
*
|
|
4
|
+
* Provides default transport handlers that `connectHandoff()` auto-selects
|
|
5
|
+
* when no custom handler has been registered for the protocol.
|
|
6
|
+
*
|
|
7
|
+
* @example Using built-in WebSocket handler (automatic)
|
|
8
|
+
* ```typescript
|
|
9
|
+
* // No manual registration needed — connectHandoff auto-selects
|
|
10
|
+
* const connection = await connectHandoff(handoff);
|
|
11
|
+
* connection.send({ type: 'message', text: 'Hello!' });
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @example Overriding a built-in handler
|
|
15
|
+
* ```typescript
|
|
16
|
+
* registerProtocolHandler('websocket', myCustomHandler);
|
|
17
|
+
* // Now connectHandoff will use your handler instead of the built-in one
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
21
|
+
// WEBSOCKET HANDLER
|
|
22
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
23
|
+
/**
|
|
24
|
+
* Built-in WebSocket protocol handler.
|
|
25
|
+
*
|
|
26
|
+
* Handles:
|
|
27
|
+
* - Connection establishment with optional token authentication
|
|
28
|
+
* - JSON message serialization/deserialization
|
|
29
|
+
* - Connection lifecycle management
|
|
30
|
+
*
|
|
31
|
+
* Authentication flow:
|
|
32
|
+
* 1. If `credentials.token` is present, sent as `{ type: 'auth', token }` message after connect
|
|
33
|
+
* 2. If `credentials.headers` are present, sent as `{ type: 'auth_headers', headers }` message
|
|
34
|
+
* (avoids leaking tokens in URLs or subprotocol encoding)
|
|
35
|
+
*
|
|
36
|
+
* Runtime requirement: `WebSocket` global (browser or Node.js 21+/polyfill)
|
|
37
|
+
*/
|
|
38
|
+
export const websocketHandler = async (handoff, options) => {
|
|
39
|
+
if (typeof WebSocket === 'undefined') {
|
|
40
|
+
throw new Error('WebSocket is not available in this runtime. ' +
|
|
41
|
+
'Use Node.js 21+ or install a WebSocket polyfill (e.g., ws).');
|
|
42
|
+
}
|
|
43
|
+
let state = 'connecting';
|
|
44
|
+
const setState = (newState) => {
|
|
45
|
+
state = newState;
|
|
46
|
+
options.onStateChange?.(newState);
|
|
47
|
+
};
|
|
48
|
+
const endpoint = handoff.endpoint;
|
|
49
|
+
const ws = new WebSocket(endpoint);
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
let settled = false;
|
|
52
|
+
const resolveOnce = (connection) => {
|
|
53
|
+
if (!settled) {
|
|
54
|
+
settled = true;
|
|
55
|
+
resolve(connection);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
const rejectOnce = (error) => {
|
|
59
|
+
if (!settled) {
|
|
60
|
+
settled = true;
|
|
61
|
+
reject(error);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const connection = {
|
|
65
|
+
get state() {
|
|
66
|
+
return state;
|
|
67
|
+
},
|
|
68
|
+
protocol: handoff.protocol,
|
|
69
|
+
endpoint: handoff.endpoint,
|
|
70
|
+
send(data) {
|
|
71
|
+
if (state !== 'connected') {
|
|
72
|
+
throw new Error('Cannot send: WebSocket is not in connected state');
|
|
73
|
+
}
|
|
74
|
+
ws.send(JSON.stringify(data));
|
|
75
|
+
},
|
|
76
|
+
close() {
|
|
77
|
+
ws.close(1000, 'Client close');
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
ws.onopen = () => {
|
|
81
|
+
// Send auth token as first message after connection (avoids leaking token in URL/logs)
|
|
82
|
+
if (handoff.credentials?.token) {
|
|
83
|
+
ws.send(JSON.stringify({ type: 'auth', token: handoff.credentials.token }));
|
|
84
|
+
}
|
|
85
|
+
if (handoff.credentials?.headers) {
|
|
86
|
+
ws.send(JSON.stringify({ type: 'auth_headers', headers: handoff.credentials.headers }));
|
|
87
|
+
}
|
|
88
|
+
setState('connected');
|
|
89
|
+
options.onConnect?.(ws);
|
|
90
|
+
resolveOnce(connection);
|
|
91
|
+
};
|
|
92
|
+
ws.onmessage = (event) => {
|
|
93
|
+
try {
|
|
94
|
+
const data = JSON.parse(String(event.data));
|
|
95
|
+
options.onMessage?.(data);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Forward raw string if not valid JSON
|
|
99
|
+
options.onMessage?.(event.data);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
ws.onerror = () => {
|
|
103
|
+
const error = new Error('WebSocket error');
|
|
104
|
+
options.onError?.(error);
|
|
105
|
+
if (state === 'connecting') {
|
|
106
|
+
setState('failed');
|
|
107
|
+
rejectOnce(error);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
ws.onclose = (event) => {
|
|
111
|
+
if (state === 'connecting') {
|
|
112
|
+
setState('failed');
|
|
113
|
+
const closeError = new Error(`WebSocket closed before connection established (${event.code}: ${event.reason || 'no reason'})`);
|
|
114
|
+
options.onError?.(closeError);
|
|
115
|
+
rejectOnce(closeError);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
setState('disconnected');
|
|
119
|
+
options.onDisconnect?.(event.code, event.reason);
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
124
|
+
// SSE HANDLER
|
|
125
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
126
|
+
/**
|
|
127
|
+
* Built-in SSE (Server-Sent Events) protocol handler.
|
|
128
|
+
*
|
|
129
|
+
* Handles:
|
|
130
|
+
* - Connection establishment via EventSource or fetch-based SSE
|
|
131
|
+
* - Token authentication via `Authorization` header (fetch) or query param (EventSource)
|
|
132
|
+
* - Custom header propagation via `credentials.headers`
|
|
133
|
+
* - JSON message deserialization from SSE `data` fields
|
|
134
|
+
* - Connection lifecycle management
|
|
135
|
+
*
|
|
136
|
+
* Authentication flow:
|
|
137
|
+
* - If custom headers or bearer token needed: uses `fetch()` with streaming body
|
|
138
|
+
* - Otherwise: uses `EventSource` with token as query parameter
|
|
139
|
+
*
|
|
140
|
+
* Runtime requirement: `EventSource` global or `fetch` with streaming support
|
|
141
|
+
*/
|
|
142
|
+
export const sseHandler = async (handoff, options) => {
|
|
143
|
+
const setState = (newState) => {
|
|
144
|
+
options.onStateChange?.(newState);
|
|
145
|
+
};
|
|
146
|
+
const hasCustomHeaders = handoff.credentials?.headers && Object.keys(handoff.credentials.headers).length > 0;
|
|
147
|
+
const hasToken = !!handoff.credentials?.token;
|
|
148
|
+
// If we need custom headers (including Authorization), use fetch-based SSE
|
|
149
|
+
// Otherwise, use EventSource with token as query param
|
|
150
|
+
if (hasCustomHeaders || hasToken) {
|
|
151
|
+
return createFetchBasedSse(handoff, options, setState);
|
|
152
|
+
}
|
|
153
|
+
return createEventSourceSse(handoff, options, setState);
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Create an SSE connection using the fetch API for custom header support.
|
|
157
|
+
*/
|
|
158
|
+
async function createFetchBasedSse(handoff, options, parentSetState) {
|
|
159
|
+
let state = 'connecting';
|
|
160
|
+
const setState = (newState) => {
|
|
161
|
+
state = newState;
|
|
162
|
+
parentSetState(newState);
|
|
163
|
+
};
|
|
164
|
+
if (typeof fetch === 'undefined') {
|
|
165
|
+
throw new Error('fetch is not available in this runtime. ' +
|
|
166
|
+
'Use Node.js 18+ or a fetch polyfill for SSE with authentication headers.');
|
|
167
|
+
}
|
|
168
|
+
const headers = {
|
|
169
|
+
Accept: 'text/event-stream',
|
|
170
|
+
'Cache-Control': 'no-cache',
|
|
171
|
+
...handoff.credentials?.headers,
|
|
172
|
+
};
|
|
173
|
+
if (handoff.credentials?.token) {
|
|
174
|
+
headers.Authorization = `Bearer ${handoff.credentials.token}`;
|
|
175
|
+
}
|
|
176
|
+
const abortController = new AbortController();
|
|
177
|
+
let response;
|
|
178
|
+
try {
|
|
179
|
+
response = await fetch(handoff.endpoint, {
|
|
180
|
+
headers,
|
|
181
|
+
signal: abortController.signal,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
setState('failed');
|
|
186
|
+
throw new Error(`SSE connection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
187
|
+
}
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
setState('failed');
|
|
190
|
+
throw new Error(`SSE connection failed with status ${response.status}`);
|
|
191
|
+
}
|
|
192
|
+
if (!response.body) {
|
|
193
|
+
setState('failed');
|
|
194
|
+
throw new Error('SSE response has no body — streaming not supported in this runtime');
|
|
195
|
+
}
|
|
196
|
+
setState('connected');
|
|
197
|
+
options.onConnect?.(response);
|
|
198
|
+
// Read SSE stream in background
|
|
199
|
+
const reader = response.body.getReader();
|
|
200
|
+
const decoder = new TextDecoder();
|
|
201
|
+
let buffer = '';
|
|
202
|
+
const readLoop = async () => {
|
|
203
|
+
try {
|
|
204
|
+
while (true) {
|
|
205
|
+
const { done, value } = await reader.read();
|
|
206
|
+
if (done)
|
|
207
|
+
break;
|
|
208
|
+
buffer += decoder.decode(value, { stream: true });
|
|
209
|
+
const lines = buffer.split('\n');
|
|
210
|
+
buffer = lines.pop() ?? '';
|
|
211
|
+
for (const line of lines) {
|
|
212
|
+
if (line.startsWith('data: ')) {
|
|
213
|
+
const raw = line.slice(6);
|
|
214
|
+
try {
|
|
215
|
+
options.onMessage?.(JSON.parse(raw));
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
options.onMessage?.(raw);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
if (!abortController.signal.aborted) {
|
|
226
|
+
options.onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
setState('disconnected');
|
|
231
|
+
options.onDisconnect?.();
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
readLoop();
|
|
235
|
+
return {
|
|
236
|
+
get state() {
|
|
237
|
+
return state;
|
|
238
|
+
},
|
|
239
|
+
protocol: handoff.protocol,
|
|
240
|
+
endpoint: handoff.endpoint,
|
|
241
|
+
send(_data) {
|
|
242
|
+
throw new Error('SSE connections are read-only. Use a separate HTTP endpoint to send data.');
|
|
243
|
+
},
|
|
244
|
+
close() {
|
|
245
|
+
abortController.abort();
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Create an SSE connection using the EventSource API.
|
|
251
|
+
*/
|
|
252
|
+
function createEventSourceSse(handoff, options, parentSetState) {
|
|
253
|
+
let state = 'connecting';
|
|
254
|
+
const setState = (newState) => {
|
|
255
|
+
state = newState;
|
|
256
|
+
parentSetState(newState);
|
|
257
|
+
};
|
|
258
|
+
if (typeof EventSource === 'undefined') {
|
|
259
|
+
throw new Error('EventSource is not available in this runtime. ' +
|
|
260
|
+
'Use a browser environment or install an EventSource polyfill.');
|
|
261
|
+
}
|
|
262
|
+
const endpoint = handoff.endpoint;
|
|
263
|
+
const eventSource = new EventSource(endpoint);
|
|
264
|
+
return new Promise((resolve, reject) => {
|
|
265
|
+
let settled = false;
|
|
266
|
+
const resolveOnce = (connection) => {
|
|
267
|
+
if (!settled) {
|
|
268
|
+
settled = true;
|
|
269
|
+
resolve(connection);
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
const rejectOnce = (error) => {
|
|
273
|
+
if (!settled) {
|
|
274
|
+
settled = true;
|
|
275
|
+
reject(error);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
const connection = {
|
|
279
|
+
get state() {
|
|
280
|
+
return state;
|
|
281
|
+
},
|
|
282
|
+
protocol: handoff.protocol,
|
|
283
|
+
endpoint: handoff.endpoint,
|
|
284
|
+
send(_data) {
|
|
285
|
+
throw new Error('SSE connections are read-only. Use a separate HTTP endpoint to send data.');
|
|
286
|
+
},
|
|
287
|
+
close() {
|
|
288
|
+
eventSource.close();
|
|
289
|
+
setState('disconnected');
|
|
290
|
+
options.onDisconnect?.();
|
|
291
|
+
},
|
|
292
|
+
};
|
|
293
|
+
eventSource.onopen = () => {
|
|
294
|
+
setState('connected');
|
|
295
|
+
options.onConnect?.(eventSource);
|
|
296
|
+
resolveOnce(connection);
|
|
297
|
+
};
|
|
298
|
+
eventSource.onmessage = (event) => {
|
|
299
|
+
try {
|
|
300
|
+
options.onMessage?.(JSON.parse(event.data));
|
|
301
|
+
}
|
|
302
|
+
catch {
|
|
303
|
+
options.onMessage?.(event.data);
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
eventSource.onerror = () => {
|
|
307
|
+
const error = new Error('SSE connection error');
|
|
308
|
+
options.onError?.(error);
|
|
309
|
+
if (state === 'connecting') {
|
|
310
|
+
setState('failed');
|
|
311
|
+
eventSource.close();
|
|
312
|
+
rejectOnce(error);
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
setState('disconnected');
|
|
316
|
+
options.onDisconnect?.();
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
322
|
+
// BUILT-IN HANDLER REGISTRY
|
|
323
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
324
|
+
/**
|
|
325
|
+
* Map of built-in protocol handlers.
|
|
326
|
+
* These are used as defaults when no custom handler is registered.
|
|
327
|
+
*/
|
|
328
|
+
export const builtinHandlers = new Map([
|
|
329
|
+
['websocket', websocketHandler],
|
|
330
|
+
['sse', sseHandler],
|
|
331
|
+
]);
|
|
332
|
+
//# sourceMappingURL=handlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handlers.js","sourceRoot":"","sources":["../src/handlers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAUH,kFAAkF;AAClF,oBAAoB;AACpB,kFAAkF;AAElF;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAoB,KAAK,EACrD,OAAsB,EACtB,OAAiC,EACJ,EAAE;IAC/B,IAAI,OAAO,SAAS,KAAK,WAAW,EAAE,CAAC;QACtC,MAAM,IAAI,KAAK,CACd,8CAA8C;YAC7C,6DAA6D,CAC9D,CAAC;IACH,CAAC;IAED,IAAI,KAAK,GAA2B,YAAY,CAAC;IAEjD,MAAM,QAAQ,GAAG,CAAC,QAAgC,EAAE,EAAE;QACrD,KAAK,GAAG,QAAQ,CAAC;QACjB,OAAO,CAAC,aAAa,EAAE,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC;IAEF,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAClC,MAAM,EAAE,GAAG,IAAI,SAAS,C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gBACR,OAAO,CAAC,SAAS,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACjC,CAAC;QACF,CAAC,CAAC;QAEF,WAAW,CAAC,OAAO,GAAG,GAAG,EAAE;YAC1B,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;YAChD,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;YAEzB,IAAI,KAAK,KAAK,YAAY,EAAE,CAAC;gBAC5B,QAAQ,CAAC,QAAQ,CAAC,CAAC;gBACnB,WAAW,CAAC,KAAK,EAAE,CAAC;gBACpB,UAAU,CAAC,KAAK,CAAC,CAAC;YACnB,CAAC;iBAAM,CAAC;gBACP,QAAQ,CAAC,cAAc,CAAC,CAAC;gBACzB,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC;YAC1B,CAAC;QACF,CAAC,CAAC;IACH,CAAC,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,4BAA4B;AAC5B,kFAAkF;AAElF;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAyC,IAAI,GAAG,CAG1E;IACD,CAAC,WAAW,EAAE,gBAAgB,CAAC;IAC/B,CAAC,KAAK,EAAE,UAAU,CAAC;CACnB,CAAC,CAAC"}
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Handoff Protocol Handlers & Utilities
|
|
3
|
+
*
|
|
4
|
+
* This module provides utilities for handling AFD handoff results, allowing
|
|
5
|
+
* clients to connect to streaming protocols (WebSocket, SSE, WebRTC, etc.)
|
|
6
|
+
* returned by handoff commands.
|
|
7
|
+
*
|
|
8
|
+
* @example Basic usage
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { DirectClient, isHandoff, connectHandoff } from '@afd/client';
|
|
11
|
+
*
|
|
12
|
+
* const result = await client.call<HandoffResult>('chat-connect', { roomId });
|
|
13
|
+
*
|
|
14
|
+
* if (result.success && isHandoff(result.data)) {
|
|
15
|
+
* const connection = await connectHandoff(result.data, {
|
|
16
|
+
* onConnect: () => console.log('Connected!'),
|
|
17
|
+
* onMessage: (msg) => console.log('Message:', msg),
|
|
18
|
+
* onDisconnect: () => console.log('Disconnected'),
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* connection.send({ type: 'message', text: 'Hello!' });
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @example Protocol handlers
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { registerProtocolHandler } from '@afd/client';
|
|
28
|
+
*
|
|
29
|
+
* // Register a custom WebSocket handler
|
|
30
|
+
* registerProtocolHandler('websocket', async (handoff, options) => {
|
|
31
|
+
* const ws = new WebSocket(handoff.endpoint);
|
|
32
|
+
* // ... setup handlers
|
|
33
|
+
* return { send: (data) => ws.send(data), close: () => ws.close() };
|
|
34
|
+
* });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
import type { HandoffCredentials, HandoffMetadata, HandoffProtocol, HandoffResult } from '@lushly-dev/afd-core';
|
|
38
|
+
import { isHandoff, isHandoffProtocol } from '@lushly-dev/afd-core';
|
|
39
|
+
import type { DirectClient } from './direct.js';
|
|
40
|
+
export { isHandoff, isHandoffProtocol };
|
|
41
|
+
export type { HandoffResult, HandoffCredentials, HandoffMetadata, HandoffProtocol };
|
|
42
|
+
/**
|
|
43
|
+
* Connection state for handoff connections.
|
|
44
|
+
*/
|
|
45
|
+
export type HandoffConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'failed';
|
|
46
|
+
/**
|
|
47
|
+
* Represents an active connection to a handoff endpoint.
|
|
48
|
+
*/
|
|
49
|
+
export interface HandoffConnection {
|
|
50
|
+
/**
|
|
51
|
+
* Send data through the connection.
|
|
52
|
+
* @param data - Data to send (will be JSON-serialized)
|
|
53
|
+
*/
|
|
54
|
+
send(data: unknown): void;
|
|
55
|
+
/**
|
|
56
|
+
* Close the connection.
|
|
57
|
+
*/
|
|
58
|
+
close(): void;
|
|
59
|
+
/**
|
|
60
|
+
* Get the current connection state.
|
|
61
|
+
*/
|
|
62
|
+
readonly state: HandoffConnectionState;
|
|
63
|
+
/**
|
|
64
|
+
* The protocol of this connection.
|
|
65
|
+
*/
|
|
66
|
+
readonly protocol: HandoffProtocol;
|
|
67
|
+
/**
|
|
68
|
+
* The endpoint URL of this connection.
|
|
69
|
+
*/
|
|
70
|
+
readonly endpoint: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Options for connecting to a handoff endpoint.
|
|
74
|
+
*/
|
|
75
|
+
export interface HandoffConnectionOptions {
|
|
76
|
+
/**
|
|
77
|
+
* Called when the connection is established.
|
|
78
|
+
* @param connection - The underlying connection (protocol-specific)
|
|
79
|
+
*/
|
|
80
|
+
onConnect?: (connection: unknown) => void;
|
|
81
|
+
/**
|
|
82
|
+
* Called when a message is received.
|
|
83
|
+
* @param message - Parsed message data
|
|
84
|
+
*/
|
|
85
|
+
onMessage?: (message: unknown) => void;
|
|
86
|
+
/**
|
|
87
|
+
* Called when the connection is closed.
|
|
88
|
+
* @param code - Close code (if available)
|
|
89
|
+
* @param reason - Close reason (if available)
|
|
90
|
+
*/
|
|
91
|
+
onDisconnect?: (code?: number, reason?: string) => void;
|
|
92
|
+
/**
|
|
93
|
+
* Called when an error occurs.
|
|
94
|
+
* @param error - Error object
|
|
95
|
+
*/
|
|
96
|
+
onError?: (error: Error) => void;
|
|
97
|
+
/**
|
|
98
|
+
* Called when connection state changes.
|
|
99
|
+
* @param state - New connection state
|
|
100
|
+
*/
|
|
101
|
+
onStateChange?: (state: HandoffConnectionState) => void;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Handler function for a specific protocol.
|
|
105
|
+
*
|
|
106
|
+
* Protocol handlers are responsible for:
|
|
107
|
+
* 1. Establishing the connection to the endpoint
|
|
108
|
+
* 2. Handling authentication with credentials
|
|
109
|
+
* 3. Managing the connection lifecycle
|
|
110
|
+
* 4. Translating protocol-specific events to HandoffConnectionOptions callbacks
|
|
111
|
+
*/
|
|
112
|
+
export type ProtocolHandler = (handoff: HandoffResult, options: HandoffConnectionOptions) => Promise<HandoffConnection>;
|
|
113
|
+
/**
|
|
114
|
+
* Register a protocol handler for a specific protocol type.
|
|
115
|
+
*
|
|
116
|
+
* @param protocol - The protocol identifier (e.g., 'websocket', 'sse', 'webrtc')
|
|
117
|
+
* @param handler - The handler function to call when connecting to this protocol
|
|
118
|
+
*
|
|
119
|
+
* @example Browser WebSocket handler
|
|
120
|
+
* ```typescript
|
|
121
|
+
* registerProtocolHandler('websocket', async (handoff, options) => {
|
|
122
|
+
* const ws = new WebSocket(handoff.endpoint);
|
|
123
|
+
*
|
|
124
|
+
* ws.onopen = () => {
|
|
125
|
+
* if (handoff.credentials?.token) {
|
|
126
|
+
* ws.send(JSON.stringify({ type: 'auth', token: handoff.credentials.token }));
|
|
127
|
+
* }
|
|
128
|
+
* options.onConnect?.(ws);
|
|
129
|
+
* };
|
|
130
|
+
*
|
|
131
|
+
* ws.onmessage = (event) => {
|
|
132
|
+
* options.onMessage?.(JSON.parse(event.data));
|
|
133
|
+
* };
|
|
134
|
+
*
|
|
135
|
+
* ws.onclose = (event) => {
|
|
136
|
+
* options.onDisconnect?.(event.code, event.reason);
|
|
137
|
+
* };
|
|
138
|
+
*
|
|
139
|
+
* return {
|
|
140
|
+
* send: (data) => ws.send(JSON.stringify(data)),
|
|
141
|
+
* close: () => ws.close(),
|
|
142
|
+
* state: 'connected',
|
|
143
|
+
* protocol: handoff.protocol,
|
|
144
|
+
* endpoint: handoff.endpoint,
|
|
145
|
+
* };
|
|
146
|
+
* });
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
export declare function registerProtocolHandler(protocol: string, handler: ProtocolHandler): void;
|
|
150
|
+
/**
|
|
151
|
+
* Unregister a protocol handler.
|
|
152
|
+
*
|
|
153
|
+
* @param protocol - The protocol identifier to unregister
|
|
154
|
+
* @returns True if a handler was removed, false if none existed
|
|
155
|
+
*/
|
|
156
|
+
export declare function unregisterProtocolHandler(protocol: string): boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Get a registered protocol handler.
|
|
159
|
+
*
|
|
160
|
+
* @param protocol - The protocol identifier
|
|
161
|
+
* @returns The handler function or undefined if not registered
|
|
162
|
+
*/
|
|
163
|
+
export declare function getProtocolHandler(protocol: string): ProtocolHandler | undefined;
|
|
164
|
+
/**
|
|
165
|
+
* Check if a protocol handler is registered.
|
|
166
|
+
*
|
|
167
|
+
* @param protocol - The protocol identifier
|
|
168
|
+
* @returns True if a handler is registered
|
|
169
|
+
*/
|
|
170
|
+
export declare function hasProtocolHandler(protocol: string): boolean;
|
|
171
|
+
/**
|
|
172
|
+
* List all registered protocol handlers.
|
|
173
|
+
*
|
|
174
|
+
* @returns Array of registered protocol identifiers
|
|
175
|
+
*/
|
|
176
|
+
export declare function listProtocolHandlers(): string[];
|
|
177
|
+
/**
|
|
178
|
+
* Clear all registered protocol handlers.
|
|
179
|
+
* Useful for testing or resetting state.
|
|
180
|
+
*/
|
|
181
|
+
export declare function clearProtocolHandlers(): void;
|
|
182
|
+
/**
|
|
183
|
+
* Connect to a handoff endpoint using the appropriate protocol handler.
|
|
184
|
+
*
|
|
185
|
+
* @param handoff - The handoff result from a command
|
|
186
|
+
* @param options - Connection options and callbacks
|
|
187
|
+
* @returns A promise that resolves to a HandoffConnection
|
|
188
|
+
* @throws Error if no handler is registered for the protocol
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```typescript
|
|
192
|
+
* const result = await client.call<HandoffResult>('chat-connect', { roomId: 'room-123' });
|
|
193
|
+
*
|
|
194
|
+
* if (result.success && result.data) {
|
|
195
|
+
* const connection = await connectHandoff(result.data, {
|
|
196
|
+
* onConnect: () => console.log('Connected!'),
|
|
197
|
+
* onMessage: (msg) => console.log('Message:', msg),
|
|
198
|
+
* onDisconnect: (code, reason) => console.log('Disconnected:', code),
|
|
199
|
+
* });
|
|
200
|
+
*
|
|
201
|
+
* connection.send({ type: 'message', text: 'Hello!' });
|
|
202
|
+
*
|
|
203
|
+
* // Later: close
|
|
204
|
+
* connection.close();
|
|
205
|
+
* }
|
|
206
|
+
* ```
|
|
207
|
+
*/
|
|
208
|
+
export declare function connectHandoff(handoff: HandoffResult, options?: HandoffConnectionOptions): Promise<HandoffConnection>;
|
|
209
|
+
/**
|
|
210
|
+
* Options for creating a reconnecting handoff connection.
|
|
211
|
+
*/
|
|
212
|
+
export interface ReconnectionOptions extends HandoffConnectionOptions {
|
|
213
|
+
/**
|
|
214
|
+
* Command to call for reconnection.
|
|
215
|
+
* This command should return a new HandoffResult.
|
|
216
|
+
*/
|
|
217
|
+
reconnectCommand?: string;
|
|
218
|
+
/**
|
|
219
|
+
* Arguments to pass to the reconnect command.
|
|
220
|
+
*/
|
|
221
|
+
reconnectArgs?: Record<string, unknown>;
|
|
222
|
+
/**
|
|
223
|
+
* Session ID for reconnection (extracted from original handoff credentials).
|
|
224
|
+
*/
|
|
225
|
+
sessionId?: string;
|
|
226
|
+
/**
|
|
227
|
+
* Maximum number of reconnection attempts.
|
|
228
|
+
* @default 5
|
|
229
|
+
*/
|
|
230
|
+
maxAttempts?: number;
|
|
231
|
+
/**
|
|
232
|
+
* Base backoff time in milliseconds.
|
|
233
|
+
* @default 1000
|
|
234
|
+
*/
|
|
235
|
+
backoffMs?: number;
|
|
236
|
+
/**
|
|
237
|
+
* Maximum backoff time in milliseconds.
|
|
238
|
+
* @default 30000
|
|
239
|
+
*/
|
|
240
|
+
maxBackoffMs?: number;
|
|
241
|
+
/**
|
|
242
|
+
* Called when a reconnection attempt starts.
|
|
243
|
+
* @param attempt - Current attempt number (1-based)
|
|
244
|
+
*/
|
|
245
|
+
onReconnect?: (attempt: number) => void;
|
|
246
|
+
/**
|
|
247
|
+
* Called when all reconnection attempts have failed.
|
|
248
|
+
*/
|
|
249
|
+
onReconnectFailed?: () => void;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Represents a reconnecting handoff connection with automatic retry logic.
|
|
253
|
+
*/
|
|
254
|
+
export interface ReconnectingHandoffConnection extends HandoffConnection {
|
|
255
|
+
/**
|
|
256
|
+
* Current reconnection attempt number (0 if not reconnecting).
|
|
257
|
+
*/
|
|
258
|
+
readonly reconnectAttempt: number;
|
|
259
|
+
/**
|
|
260
|
+
* Whether the connection is currently attempting to reconnect.
|
|
261
|
+
*/
|
|
262
|
+
readonly isReconnecting: boolean;
|
|
263
|
+
/**
|
|
264
|
+
* Manually trigger a reconnection.
|
|
265
|
+
*/
|
|
266
|
+
reconnect(): Promise<void>;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Create a reconnecting handoff connection with automatic retry logic.
|
|
270
|
+
*
|
|
271
|
+
* This helper wraps a standard handoff connection and adds:
|
|
272
|
+
* - Automatic reconnection on disconnect
|
|
273
|
+
* - Exponential backoff between attempts
|
|
274
|
+
* - Session resumption via reconnect command
|
|
275
|
+
*
|
|
276
|
+
* @param client - The DirectClient to use for reconnection commands
|
|
277
|
+
* @param handoff - The initial handoff result
|
|
278
|
+
* @param options - Reconnection options and callbacks
|
|
279
|
+
* @returns A promise that resolves to a ReconnectingHandoffConnection
|
|
280
|
+
*
|
|
281
|
+
* @example
|
|
282
|
+
* ```typescript
|
|
283
|
+
* const result = await client.call<HandoffResult>('chat-connect', { roomId: 'room-123' });
|
|
284
|
+
*
|
|
285
|
+
* if (result.success && result.data) {
|
|
286
|
+
* const connection = await createReconnectingHandoff(client, result.data, {
|
|
287
|
+
* reconnectCommand: 'chat-reconnect',
|
|
288
|
+
* sessionId: result.data.credentials?.sessionId,
|
|
289
|
+
*
|
|
290
|
+
* onConnect: () => console.log('Connected'),
|
|
291
|
+
* onReconnect: (attempt) => console.log(`Reconnecting (attempt ${attempt})`),
|
|
292
|
+
* onReconnectFailed: () => console.log('Reconnection failed'),
|
|
293
|
+
* onMessage: (msg) => handleMessage(msg),
|
|
294
|
+
* onDisconnect: () => console.log('Disconnected'),
|
|
295
|
+
* });
|
|
296
|
+
* }
|
|
297
|
+
* ```
|
|
298
|
+
*/
|
|
299
|
+
export declare function createReconnectingHandoff(client: DirectClient, handoff: HandoffResult, options?: ReconnectionOptions): Promise<ReconnectingHandoffConnection>;
|
|
300
|
+
/**
|
|
301
|
+
* Build a WebSocket URL with authentication token as query parameter.
|
|
302
|
+
*
|
|
303
|
+
* @param endpoint - The base WebSocket endpoint
|
|
304
|
+
* @param credentials - Optional credentials with token
|
|
305
|
+
* @returns The URL with token appended if provided
|
|
306
|
+
*/
|
|
307
|
+
export declare function buildAuthenticatedEndpoint(endpoint: string, credentials?: HandoffCredentials): string;
|
|
308
|
+
/**
|
|
309
|
+
* Parse a handoff endpoint URL and extract connection details.
|
|
310
|
+
*
|
|
311
|
+
* @param endpoint - The endpoint URL
|
|
312
|
+
* @returns Parsed URL components
|
|
313
|
+
*/
|
|
314
|
+
export declare function parseHandoffEndpoint(endpoint: string): {
|
|
315
|
+
protocol: string;
|
|
316
|
+
host: string;
|
|
317
|
+
port: number | null;
|
|
318
|
+
path: string;
|
|
319
|
+
secure: boolean;
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* Check if handoff credentials have expired.
|
|
323
|
+
*
|
|
324
|
+
* @param handoff - The handoff result to check
|
|
325
|
+
* @returns True if credentials have expired
|
|
326
|
+
*/
|
|
327
|
+
export declare function isHandoffExpired(handoff: HandoffResult): boolean;
|
|
328
|
+
/**
|
|
329
|
+
* Get the time until handoff credentials expire.
|
|
330
|
+
*
|
|
331
|
+
* @param handoff - The handoff result to check
|
|
332
|
+
* @returns Milliseconds until expiration, or null if no expiration set
|
|
333
|
+
*/
|
|
334
|
+
export declare function getHandoffTTL(handoff: HandoffResult): number | null;
|
|
335
|
+
//# sourceMappingURL=handoff.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handoff.d.ts","sourceRoot":"","sources":["../src/handoff.ts"],"names":[],"mappings":"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