-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.js
More file actions
1589 lines (1474 loc) · 54.7 KB
/
Copy pathclient.js
File metadata and controls
1589 lines (1474 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { writable, derived } from 'svelte/store';
/** @type {ReturnType<typeof createConnection> | null} */
let singleton = null;
/** @type {'explicit' | 'implicit' | ''} */
let singletonCreatedBy = '';
/**
* Ensure the singleton connection exists.
* @param {import('./client.js').ConnectOptions} [options]
* @param {boolean} [explicit]
* @returns {ReturnType<typeof createConnection>}
*/
function ensureConnection(options, explicit = false) {
if (!singleton) {
singletonCreatedBy = explicit ? 'explicit' : 'implicit';
singleton = createConnection(options || {});
}
return singleton;
}
/**
* Connect to the WebSocket server.
*
* Returns a singleton - calling `connect()` multiple times returns the same
* connection. Safe to call from any component or module.
*
* Most users don't need this - use `on()` and `status` directly instead.
*
* @param {import('./client.js').ConnectOptions} [options]
* @returns {import('./client.js').WSConnection}
*/
export function connect(options = {}) {
if (singleton && singletonCreatedBy === 'implicit' && Object.keys(options).length > 0) {
console.warn(
'[ws] connect() was called with options, but the connection already exists ' +
'(created automatically by on(), status, or ready()). ' +
'Your options are ignored. Call connect() before using other client functions.\n' +
' See: https://svti.me/client-connect'
);
}
return ensureConnection(options, true);
}
/**
* Get a reactive Svelte store for a topic (and optionally a specific event).
* Auto-connects and auto-subscribes - this is the only function most users need.
*
* @overload
* @param {string} topic - Topic to subscribe to
* @returns {import('svelte/store').Readable<import('./client.js').WSEvent | null>}
* Full event envelope `{ topic, event, data }`.
*
* @overload
* @param {string} topic - Topic to subscribe to
* @param {string} event - Filter to a specific event name
* @returns {import('svelte/store').Readable<unknown>}
* Just the `data` payload - no envelope.
*
* @param {string} topic
* @param {string} [event]
*/
export function on(topic, event) {
const conn = ensureConnection();
if (event !== undefined) {
return conn._onEvent(topic, event);
}
const store = conn.on(topic);
return store;
}
/**
* Create a store that subscribes to a topic derived from a reactive value.
* When the source store changes, the subscription automatically switches to
* the new topic and the old one is released.
*
* Useful when the topic depends on runtime state like a user ID, selected item,
* or route parameter - no manual subscribe/unsubscribe lifecycle to manage.
*
* @template T
* @param {(value: T) => string} topicFn - Maps the source store's value to a topic name
* @param {import('svelte/store').Readable<T>} store - Reactive input value
* @returns {import('svelte/store').Readable<import('./client.js').WSEvent | null>}
*
* @example
* ```svelte
* <script>
* import { page } from '$app/stores';
* import { onDerived } from 'svelte-adapter-uws/client';
* import { derived } from 'svelte/store';
*
* // Subscribe to a topic based on the current page's item ID
* const roomId = derived(page, ($page) => $page.params.id);
* const messages = onDerived((id) => `room:${id}`, roomId);
* </script>
*
* {#if $messages}
* <p>{$messages.event}: {JSON.stringify($messages.data)}</p>
* {/if}
* ```
*/
export function onDerived(topicFn, store) {
return derived(store, ($value, set) => {
if ($value == null) {
set(null);
return;
}
// on() is ref-counted - the returned unsubscribe function decrements
// the ref count and releases the server subscription when it hits zero.
// derived() calls this cleanup whenever the source store produces a new
// value or when all subscribers of the derived store are gone.
return on(topicFn($value)).subscribe(set);
}, null);
}
/**
* Readable store - connection status. Auto-connects on first access.
*
* Five states drive distinct UI affordances:
* - `'connecting'` - establishing a connection (initial attempt or retry)
* - `'open'` - connected, live data is flowing
* - `'suspended'` - WS is technically open but the tab is in the background;
* server may close idle backgrounded sockets, so live data is best-effort
* - `'disconnected'` - lost connection, will retry automatically
* - `'failed'` - terminal: auth denied, max retries exhausted, or `close()` called
*
* @type {import('svelte/store').Readable<'connecting' | 'open' | 'suspended' | 'disconnected' | 'failed'>}
*/
export const status = {
subscribe(fn) {
return ensureConnection().status.subscribe(fn);
}
};
/**
* Readable store of the latest subscribe-denied response from the server.
* Each entry is `{ topic, reason, ref }` where `reason` is one of the
* built-in codes (`'UNAUTHENTICATED'`, `'FORBIDDEN'`, `'INVALID_TOPIC'`,
* `'RATE_LIMITED'`) or any custom string the server's `subscribe` hook
* returned. The store stays at `null` until the first denial.
*
* @type {import('svelte/store').Readable<{ topic: string, reason: string, ref: number | string } | null>}
*/
export const denials = {
subscribe(fn) {
return ensureConnection().denials.subscribe(fn);
}
};
/**
* Readable store - cause of the most recent non-open status transition.
* `null` while connected (or before any failure has occurred). Set when
* the connection drops via a recognised close code, when the reconnect
* cap is hit, or when the auth preflight fails. Cleared on the next
* successful `'open'`. Does not fire for an intentional `close()` call -
* `status === 'failed'` plus `failure === null` is the deliberately-ended
* state.
*
* Use this alongside `status` to render targeted UI per failure cause:
* "Session expired" for `class: 'TERMINAL'`, "Server is busy" for
* `'THROTTLE'`, generic "Reconnecting" for `'RETRY'`, etc.
*
* @type {import('svelte/store').Readable<import('./client.js').Failure | null>}
*/
export const failure = {
subscribe(fn) {
return ensureConnection().failure.subscribe(fn);
}
};
/**
* Install a handler for server-initiated requests. The server may call
* `platform.request(ws, event, data)` and await your reply; this is
* where that lands. Return a value (sync or async) and the framework
* sends it back as the reply. Throw or reject to send an error reply
* the server will surface as a Promise rejection.
*
* Only one handler may be installed at a time. Calling `onRequest`
* again replaces the previous handler. Returns an unsubscribe function
* that clears the handler if it is still the active one. With no
* handler installed, incoming request frames are dropped and the
* server's awaiting Promise times out.
*
* @param {(event: string, data: unknown) => unknown | Promise<unknown>} handler
* @returns {() => void}
*/
export function onRequest(handler) {
return ensureConnection().onRequest(handler);
}
/**
* Returns a promise that resolves when the WebSocket connection is open.
* Auto-connects if not already connected.
*
* @returns {Promise<void>}
*/
export function ready() {
if (typeof window === 'undefined' && !(singleton && singleton._hasUrl)) return Promise.resolve();
const conn = ensureConnection();
return new Promise((resolve, reject) => {
let settled = false;
/** @type {(() => void) | null} */
let statusUnsub = null;
/** @type {(() => void) | null} */
let permaUnsub = null;
function cleanup() {
if (settled) return;
settled = true;
queueMicrotask(() => {
statusUnsub?.();
permaUnsub?.();
});
}
statusUnsub = conn.status.subscribe((s) => {
// 'suspended' means WS is open but tab is in the background -
// the connection is established, so ready() resolves there too.
if (s === 'open' || s === 'suspended') { cleanup(); resolve(); }
});
permaUnsub = conn._permaClosed.subscribe((dead) => {
if (dead) {
cleanup();
reject(new Error('WebSocket connection permanently closed'));
}
});
});
}
// Storage adapters for the live-CRUD reducer pattern shared by crud()
// and lookup() (with and without maxAge). Each adapter implements
// create / update / delete for a particular collection shape (Array or
// Record). The keyOf(item) extractor lets callers control whether keys
// are coerced to string (e.g. for the maxAge variants whose long-lived
// timestamp Map needs primitive-stable keys) or left as-is.
const arrayCrudStorage = {
create(list, item, { prepend }) {
return prepend ? [item, ...list] : [...list, item];
},
update(list, item, { keyOf }) {
const id = keyOf(item);
return list.map((x) => keyOf(x) === id ? item : x);
},
delete(list, item, { keyOf }) {
const id = keyOf(item);
return list.filter((x) => keyOf(x) !== id);
}
};
const recordCrudStorage = {
create(map, item, { keyOf }) {
return { ...map, [keyOf(item)]: item };
},
update(map, item, { keyOf }) {
return { ...map, [keyOf(item)]: item };
},
delete(map, item, { keyOf }) {
const id = keyOf(item);
if (!(id in map)) return map;
const { [id]: _, ...rest } = map;
return rest;
}
};
/**
* Apply a single created / updated / deleted event to a collection.
* Returns the new collection, or the original reference if the event
* was not a CRUD verb or the data was not an object.
*
* @template S
* @param {S} state
* @param {string} event
* @param {unknown} data
* @param {{ create: Function, update: Function, delete: Function }} storage
* @param {{ keyOf: (item: any) => unknown, prepend?: boolean }} options
* @returns {S}
*/
function applyCrudReducer(state, event, data, storage, options) {
if (data == null || typeof data !== 'object') return state;
if (event === 'created') return storage.create(state, data, options);
if (event === 'updated') return storage.update(state, data, options);
if (event === 'deleted') return storage.delete(state, data, options);
return state;
}
/**
* Live CRUD list - one line for real-time collections.
* Auto-connects, auto-subscribes, and auto-handles created/updated/deleted events.
*
* When `maxAge` is set, entries that haven't been created or updated
* within that window are automatically removed from the list.
*
* @template T
* @param {string} topic - Topic to subscribe to
* @param {T[]} [initial] - Starting data (e.g. from a load function)
* @param {{ key?: string, prepend?: boolean, maxAge?: number }} [options] - Options
* @returns {import('svelte/store').Readable<T[]>}
*/
export function crud(topic, initial = [], options = {}) {
const key = options.key || 'id';
const prepend = options.prepend || false;
const maxAge = options.maxAge;
if (maxAge == null || maxAge <= 0) {
const opts = { keyOf: (/** @type {any} */ x) => x[key], prepend };
return on(topic).scan(/** @type {any[]} */ (initial), (list, { event, data }) =>
applyCrudReducer(list, event, data, arrayCrudStorage, opts)
);
}
// maxAge mode: track timestamps per key, sweep on interval
const conn = ensureConnection();
const source = conn.on(topic);
const keyOf = (/** @type {any} */ x) => String(x[key]);
const reducerOpts = { keyOf, prepend };
/** @type {any[]} */
let list = [...initial];
/** @type {Map<string, number>} */
const timestamps = new Map();
const now = Date.now();
for (const item of initial) {
timestamps.set(keyOf(item), now);
}
const output = writable(list);
/** @type {(() => void) | null} */
let sourceUnsub = null;
/** @type {ReturnType<typeof setInterval> | null} */
let sweepTimer = null;
let subCount = 0;
function sweep() {
const cutoff = Date.now() - /** @type {number} */ (maxAge);
let changed = false;
for (const [id, ts] of timestamps) {
if (ts < cutoff) {
timestamps.delete(id);
const before = list.length;
list = list.filter((item) => keyOf(item) !== id);
if (list.length !== before) changed = true;
}
}
if (changed) output.set(list);
}
function start() {
sourceUnsub = source.subscribe((event) => {
if (event === null) return;
const { event: evt, data } = event;
if (evt !== 'created' && evt !== 'updated' && evt !== 'deleted') return;
if (data == null || typeof data !== 'object') return;
const id = keyOf(data);
if (evt === 'deleted') timestamps.delete(id);
else timestamps.set(id, Date.now());
list = applyCrudReducer(list, evt, data, arrayCrudStorage, reducerOpts);
output.set(list);
});
sweepTimer = setInterval(sweep, Math.max(maxAge / 2, 1000));
}
function stop() {
if (sourceUnsub) { sourceUnsub(); sourceUnsub = null; }
if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
list = [...initial];
const now = Date.now();
timestamps.clear();
for (const item of initial) {
timestamps.set(keyOf(item), now);
}
output.set(list);
}
return {
subscribe(fn) {
if (subCount++ === 0) start();
const unsub = output.subscribe(fn);
return () => {
unsub();
if (--subCount === 0) stop();
};
}
};
}
/**
* Live keyed object - like `crud()` but returns a `Record` keyed by ID.
* Better for dashboards and fast lookups.
*
* When `maxAge` is set, entries that haven't been created or updated
* within that window are automatically removed. Useful for presence,
* cursors, or any state backed by an external store with TTL expiry.
*
* @template T
* @param {string} topic - Topic to subscribe to
* @param {T[]} [initial] - Starting data (e.g. from a load function)
* @param {{ key?: string, maxAge?: number }} [options] - Options
* @returns {import('svelte/store').Readable<Record<string, T>>}
*/
export function lookup(topic, initial = [], options = {}) {
const key = options.key || 'id';
const maxAge = options.maxAge;
/** @type {Record<string, any>} */
const initialMap = {};
for (const item of initial) {
initialMap[/** @type {any} */ (item)[key]] = item;
}
if (maxAge == null || maxAge <= 0) {
const opts = { keyOf: (/** @type {any} */ x) => x[key] };
return on(topic).scan(initialMap, (map, { event, data }) =>
applyCrudReducer(map, event, data, recordCrudStorage, opts)
);
}
// maxAge mode: track timestamps per key, sweep on interval
const conn = ensureConnection();
const source = conn.on(topic);
const keyOf = (/** @type {any} */ x) => x[key];
const reducerOpts = { keyOf };
/** @type {Record<string, any>} */
let map = { ...initialMap };
/** @type {Map<string, number>} */
const timestamps = new Map();
const now = Date.now();
for (const id in initialMap) {
timestamps.set(id, now);
}
const output = writable(map);
/** @type {(() => void) | null} */
let sourceUnsub = null;
/** @type {ReturnType<typeof setInterval> | null} */
let sweepTimer = null;
let subCount = 0;
function sweep() {
const cutoff = Date.now() - /** @type {number} */ (maxAge);
let changed = false;
for (const [id, ts] of timestamps) {
if (ts < cutoff) {
timestamps.delete(id);
if (id in map) {
const { [id]: _, ...rest } = map;
map = rest;
changed = true;
}
}
}
if (changed) output.set(map);
}
function start() {
sourceUnsub = source.subscribe((event) => {
if (event === null) return;
const { event: evt, data } = event;
if (evt !== 'created' && evt !== 'updated' && evt !== 'deleted') return;
if (data == null || typeof data !== 'object') return;
const id = keyOf(data);
if (evt === 'deleted') timestamps.delete(id);
else timestamps.set(id, Date.now());
const next = applyCrudReducer(map, evt, data, recordCrudStorage, reducerOpts);
if (next === map) return;
map = next;
output.set(map);
});
// Sweep at half the maxAge interval for responsive cleanup
// without burning cycles on very short intervals
sweepTimer = setInterval(sweep, Math.max(maxAge / 2, 1000));
}
function stop() {
if (sourceUnsub) { sourceUnsub(); sourceUnsub = null; }
if (sweepTimer) { clearInterval(sweepTimer); sweepTimer = null; }
map = { ...initialMap };
const now = Date.now();
timestamps.clear();
for (const id in initialMap) {
timestamps.set(id, now);
}
output.set(map);
}
return {
subscribe(fn) {
if (subCount++ === 0) start();
const unsub = output.subscribe(fn);
return () => {
unsub();
if (--subCount === 0) stop();
};
}
};
}
/**
* Ring buffer of the last N events on a topic.
* Perfect for chat, activity feeds, and notifications.
*
* @template T
* @param {string} topic - Topic to subscribe to
* @param {number} [max] - Maximum number of events to keep
* @param {T[]} [initial] - Starting data
* @returns {import('svelte/store').Readable<import('./client.js').WSEvent<T>[]>}
*/
export function latest(topic, max = 50, initial = []) {
return on(topic).scan(/** @type {any[]} */ (initial), (buffer, event) => {
const next = [...buffer, event];
return next.length > max ? next.slice(next.length - max) : next;
});
}
/**
* Live counter store - handles set/increment/decrement events.
*
* @param {string} topic - Topic to subscribe to
* @param {number} [initial] - Starting value
* @returns {import('svelte/store').Readable<number>}
*/
export function count(topic, initial = 0) {
return on(topic).scan(initial, (n, { event, data }) => {
if (event === 'set') return typeof data === 'number' ? data : n;
if (event === 'increment') return n + (typeof data === 'number' ? data : 1);
if (event === 'decrement') return n - (typeof data === 'number' ? data : 1);
return n;
});
}
/**
* Wait for a specific event on a topic. Resolves once and unsubscribes.
*
* @param {string} topic - Topic to listen on
* @param {string} [event] - Optional event name to filter on
* @param {{ timeout?: number }} [options] - Options
* @returns {Promise<unknown>}
*/
export function once(topic, event, options) {
// Allow once(topic, { timeout }) shorthand (skip event)
if (typeof event === 'object' && event !== null) {
options = event;
event = undefined;
}
const timeout = options?.timeout;
const conn = ensureConnection();
return new Promise((resolve, reject) => {
const store = event !== undefined ? conn._onEvent(topic, event) : conn.on(topic);
let settled = false;
let first = true;
let timer;
function cleanup() {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
queueMicrotask(() => unsub());
}
const unsub = store.subscribe((data) => {
// Skip the synchronous initial emission - stores fire immediately
// with their current value, which may be stale from a previous event
if (first) { first = false; return; }
if (data !== null) {
cleanup();
resolve(data);
}
});
if (timeout !== undefined) {
timer = setTimeout(() => {
cleanup();
reject(new Error(`once('${topic}'${event ? `, '${event}'` : ''}) timed out after ${timeout}ms`));
}, timeout);
}
});
}
// Close codes that indicate the server has permanently rejected this client.
// Reconnecting would be pointless (credentials invalid, policy violation, etc.).
const TERMINAL_CLOSE_CODES = new Set([
1008, // Policy Violation
4401, // Unauthorized (custom)
4403, // Forbidden (custom)
]);
// Close codes indicating server-side throttling. Reconnect is still attempted
// but we jump ahead in the backoff curve to avoid hammering a rate-limited server.
const THROTTLE_CLOSE_CODES = new Set([
4429, // Rate limited (custom)
]);
/**
* Classify a WebSocket close code into one of three reconnect behaviors.
*
* - `'TERMINAL'`: the server has permanently rejected this client.
* Reconnecting would be pointless. The client store transitions to a
* permanently-closed state and stops trying. Codes: 1008 (policy
* violation), 4401 (unauthorized), 4403 (forbidden).
* - `'THROTTLE'`: the server is rate-limiting. Reconnect is still
* attempted but the client jumps ahead in the backoff curve to avoid
* hammering a busy server. Code: 4429 (too many requests).
* - `'RETRY'`: every other code, including normal closes (1000/1001) and
* abnormal ones (1006/1011/1012). The client reconnects with the
* standard backoff curve.
*
* Pure: no I/O, no globals. Suitable for unit tests.
*
* @param {number | undefined} code
* @returns {'TERMINAL' | 'THROTTLE' | 'RETRY'}
*/
export function classifyCloseCode(code) {
if (TERMINAL_CLOSE_CODES.has(code)) return 'TERMINAL';
if (THROTTLE_CLOSE_CODES.has(code)) return 'THROTTLE';
return 'RETRY';
}
/**
* Compute the next reconnect delay using exponential backoff with
* proportional jitter.
*
* The capped delay is `min(base * 2.2^attempt, maxDelay)`. A random factor
* in `[0.75, 1.25]` is then applied multiplicatively, so the final delay
* spans +/- 25% of the capped value. Multiplicative jitter keeps spread
* meaningful at high attempt counts: with 10K clients all reconnecting
* after a server restart, additive +/- 500ms jitter clusters reconnects
* inside a 1 second window; proportional jitter spreads them across
* a window proportional to the current backoff.
*
* The 2.2 exponent with a 5 minute cap is aggressive enough to back off
* fast under sustained server pain (the default 3 second base hits the
* cap by attempt 6) and gentle enough that a brief restart resolves
* before the user notices.
*
* Pure: no I/O, no globals. Pass a deterministic `randFactor` for
* reproducible assertions in tests.
*
* The default `Math.random()` is the correct primitive here: this value
* is reconnect-backoff jitter, used to spread retries across a fleet so a
* server restart does not hit a thundering-herd. Not security-relevant -
* the randFactor never crosses a trust boundary.
*
* @param {number} base base interval in ms (e.g. 3000)
* @param {number} maxDelay cap in ms (e.g. 300000)
* @param {number} attempt zero-based attempt counter
* @param {number} [randFactor] random factor in [0, 1); defaults to Math.random()
* @returns {number}
*/
export function nextReconnectDelay(base, maxDelay, attempt, randFactor = Math.random()) {
const capped = Math.min(base * Math.pow(2.2, attempt), maxDelay);
return capped * (0.75 + randFactor * 0.5);
}
/**
* @param {import('./client.js').ConnectOptions} options
* @returns {import('./client.js').WSConnection & { _onEvent: (topic: string, event: string) => import('svelte/store').Readable<unknown> }}
*/
function createConnection(options) {
const {
url,
path = '/ws',
reconnectInterval = 3000,
maxReconnectInterval = 300000,
maxReconnectAttempts = Infinity,
debug = false,
auth = false
} = options;
// Resolve the auth preflight path. `auth: true` -> default '/__ws/auth',
// `auth: '/custom'` -> use the provided path, `auth: false` (default) -> disabled.
/** @type {string | null} */
const authPath = auth === true ? '/__ws/auth' : (typeof auth === 'string' && auth) ? auth : null;
/** @type {WebSocket | null} */
let ws = null;
/** @type {ReturnType<typeof setTimeout> | null} */
let reconnectTimer = null;
/** @type {ReturnType<typeof setInterval> | null} */
let activityTimer = null;
/** @type {Promise<boolean> | null} deduped in-flight auth preflight */
let authInFlight = null;
let attempt = 0;
let intentionallyClosed = false;
// Set when the server permanently rejects us (terminal close code) or when
// retries are exhausted. Distinct from intentionallyClosed (user-initiated).
// Both prevent the visibility handler from triggering a reconnect.
let terminalClosed = false;
// Set when the page is hidden - signals that the next disconnect may be
// browser-initiated and should reconnect immediately when the tab resumes.
let hiddenDisconnect = false;
// Timestamp of the last message received from the server. Used to detect
// zombie connections - cases where onclose was suppressed by browser throttling.
let lastServerMessage = Date.now();
// 2.5x the server's 120s idle timeout. If the server has been completely
// silent for this long while the socket appears open, it is likely a zombie.
const SERVER_TIMEOUT_MS = 150000;
/** @type {Set<string>} */
const subscribedTopics = new Set();
/** @type {Map<string, number>} */
const topicRefCounts = new Map();
// Highest seq seen per topic. Sent back to the server on reconnect via
// the resume frame so the user's resume hook can replay anything we
// missed during the disconnect window. Only topics that the server is
// stamping with seq end up here; opted-out topics ({ seq: false }) are
// skipped.
/** @type {Map<string, number>} */
const lastSeenSeqs = new Map();
// sessionStorage key for the previous connection's session id. Scoped
// by ws path so two clients on different endpoints in the same tab do
// not collide. Read in-place rather than cached so private-mode tabs
// (where sessionStorage throws) silently fall back to no-resume.
const sessionStorageKey = 'svelte-adapter-uws.session.' + path;
function storedSessionId() {
try {
return typeof sessionStorage !== 'undefined' ? sessionStorage.getItem(sessionStorageKey) : null;
} catch { return null; }
}
function storeSessionId(id) {
try {
if (typeof sessionStorage !== 'undefined') sessionStorage.setItem(sessionStorageKey, id);
} catch {}
}
/** @type {Array<string | ArrayBuffer | ArrayBufferView>} */
const sendQueue = [];
const MAX_QUEUE_SIZE = 1000;
/** @type {import('svelte/store').Writable<import('./client.js').WSEvent | null>} */
const eventsStore = writable(null);
/** @type {Map<string, import('svelte/store').Writable<import('./client.js').WSEvent | null>>} */
const topicStores = new Map();
/** @type {Map<string, import('svelte/store').Writable<unknown>>} */
const eventStores = new Map();
/** @type {import('svelte/store').Writable<'connecting' | 'open' | 'suspended' | 'disconnected' | 'failed'>} */
const statusStore = writable('disconnected');
// Set status to 'open' normally, or 'suspended' if the tab is in the
// background. Centralised so onopen and the visibility handler stay
// in sync without duplicating the document.hidden check.
function setStatusOpen() {
if (typeof document !== 'undefined' && document.hidden) {
statusStore.set('suspended');
} else {
statusStore.set('open');
}
}
// Subscribe ref counter and the subscribe-denied surface. Every
// subscribe / subscribe-batch the client emits carries a numeric ref
// so the server can reply with a per-topic { type: 'subscribed' } or
// { type: 'subscribe-denied', reason } ack. The latest denial is
// exposed via the `denials` Readable for consumers that want to show
// a banner ("Access denied") or reason-coded retry.
let nextSubscribeRef = 1;
/** @type {import('svelte/store').Writable<{ topic: string, reason: string, ref: number | string } | null>} */
const denialsStore = writable(null);
// Wire-frame ceilings for subscribe-batch chunking. Match the server's
// control-message limits: 8192 byte parse ceiling and 256-topic batch
// cap. The envelope-bytes prelude leaves room for the {type, ref}
// scaffolding around the topics array.
const SUBSCRIBE_BATCH_ENVELOPE_BYTES = 50;
const SUBSCRIBE_BATCH_MAX_BYTES = 8000;
const SUBSCRIBE_BATCH_MAX_TOPICS = 200;
const subscribeBatchEncoder = new TextEncoder();
/**
* Chunk a list of topics into subscribe-batch payloads bounded by the
* server's parse ceiling and topic cap. Pure helper shared by the
* reconnect-time resubscribe path and the initial-mount microtask
* flush so the two cannot drift on the byte / topic limits.
* @param {string[]} topics
* @returns {string[][]}
*/
function chunkTopicsForBatch(topics) {
const out = [];
let chunk = [];
let chunkBytes = SUBSCRIBE_BATCH_ENVELOPE_BYTES;
for (const t of topics) {
const entryBytes = subscribeBatchEncoder.encode(JSON.stringify(t)).length + 1;
if (chunk.length > 0 && (chunk.length >= SUBSCRIBE_BATCH_MAX_TOPICS || chunkBytes + entryBytes > SUBSCRIBE_BATCH_MAX_BYTES)) {
out.push(chunk);
chunk = [];
chunkBytes = SUBSCRIBE_BATCH_ENVELOPE_BYTES;
}
chunk.push(t);
chunkBytes += entryBytes;
}
if (chunk.length > 0) out.push(chunk);
return out;
}
// Initial-mount subscribe coalescer. Multiple subscribe(topic) calls
// landing in the same microtask collapse to a single subscribe-batch
// frame, so a page mounting N streams triggers the server's
// subscribeBatch hook once instead of the per-topic subscribe hook
// N times. Single-topic case stays as plain subscribe for the
// minimal-change wire shape. Topics are also added to subscribedTopics
// upfront, so a disconnect before the microtask fires loses nothing -
// the reopen's resubscribe-batch path picks them up.
/** @type {string[] | null} */
let pendingSubscribes = null;
function flushPendingSubscribes() {
const batch = pendingSubscribes;
pendingSubscribes = null;
if (!batch || batch.length === 0) return;
if (!ws || ws.readyState !== WebSocket.OPEN) return;
if (batch.length === 1) {
const topic = batch[0];
if (debug) console.log('[ws] subscribe ->', topic);
ws.send(JSON.stringify({ type: 'subscribe', topic, ref: nextSubscribeRef++ }));
return;
}
for (const chunk of chunkTopicsForBatch(batch)) {
if (debug) console.log('[ws] subscribe-batch ->', chunk);
ws.send(JSON.stringify({ type: 'subscribe-batch', topics: chunk, ref: nextSubscribeRef++ }));
}
}
// Cause of the most recent non-open status transition. Set on
// TERMINAL/THROTTLE/RETRY close codes, on the reconnect cap being
// hit (EXHAUSTED), and on auth-preflight failures (AUTH). Cleared
// on the next successful 'open'. `status === 'failed'` plus
// `failure === null` is the intentional-close state - the user
// terminated the connection, not the network.
/** @type {import('svelte/store').Writable<import('./client.js').Failure | null>} */
const failureStore = writable(null);
let lastCloseCode = 0;
let lastCloseReason = '';
// Single onRequest handler. Server-initiated push-with-reply lands
// here: server sends { type: 'request', ref, event, data }, this
// callback returns the reply value (sync or async) and the framework
// sends { type: 'reply', ref, data } back. A throwing / rejecting
// handler turns into { type: 'reply', ref, error: <message> } so the
// server's awaiting Promise rejects symmetrically. With no handler
// installed, request frames are dropped silently and the server's
// request times out.
/** @type {((event: string, data: unknown) => unknown | Promise<unknown>) | null} */
let requestHandler = null;
// Set to true when no more reconnects will ever be attempted.
// Consumers (ready()) watch this to reject instead of waiting forever.
/** @type {import('svelte/store').Writable<boolean>} */
const permaClosedStore = writable(false);
function getUrl() {
if (url) return url;
if (typeof window === 'undefined') return '';
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${protocol}//${window.location.host}${path}`;
}
/**
* Build the HTTP URL for the auth preflight. Mirrors getUrl() but emits
* http/https instead of ws/wss so same-origin cookies flow correctly.
* Returns null in SSR or when auth is disabled.
*/
function getAuthUrl() {
if (!authPath) return null;
if (url) {
try {
const wsUrl = new URL(url);
const httpScheme = wsUrl.protocol === 'wss:' ? 'https:' : 'http:';
return httpScheme + '//' + wsUrl.host + authPath;
} catch {
return null;
}
}
if (typeof window === 'undefined') return null;
return window.location.origin + authPath;
}
/**
* Run the auth preflight. Returns one of:
* - `'ok'` - request accepted (2xx). Open the socket.
* - `'unauthorized'` - server rejected with 4xx. Terminal: the user is
* not authenticated and retrying won't help without new credentials.
* - `'transient'` - 5xx or network error. Fall back to normal reconnect
* backoff so the preflight retries alongside the socket.
*
* Deduped: concurrent doConnect() calls share a single in-flight fetch.
*
* Returns the outcome plus the HTTP status (0 on network error) and a
* human-readable reason label, so callers can populate the failure
* store without repeating the fetch logic.
*
* @returns {Promise<{ outcome: 'ok' | 'unauthorized' | 'transient', status: number, reason: string }>}
*/
function runAuth() {
if (!authPath) return Promise.resolve({ outcome: 'ok', status: 0, reason: '' });
if (authInFlight) return authInFlight;
const target = getAuthUrl();
if (!target) return Promise.resolve({ outcome: 'ok', status: 0, reason: '' });
authInFlight = (async () => {
try {
const resp = await fetch(target, {
method: 'POST',
credentials: 'include',
headers: { 'x-requested-with': 'svelte-adapter-uws' }
});
if (debug) console.log('[ws] auth preflight status=%d', resp.status);
if (resp.ok) return { outcome: 'ok', status: resp.status, reason: '' };
if (resp.status >= 400 && resp.status < 500) {
return { outcome: 'unauthorized', status: resp.status, reason: resp.statusText || 'unauthorized' };
}
return { outcome: 'transient', status: resp.status, reason: resp.statusText || 'service unavailable' };
} catch (err) {
if (debug) console.warn('[ws] auth preflight network error:', err);
return { outcome: 'transient', status: 0, reason: 'network error' };
} finally {
authInFlight = null;
}
})();
return authInFlight;
}
function doConnect() {
if (!url && typeof window === 'undefined') return;
if (ws && (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN)) return;
statusStore.set('connecting');
if (authPath) {
runAuth().then((result) => {
if (intentionallyClosed || terminalClosed) return;
if (result.outcome === 'unauthorized') {
// Server rejected the request with a 4xx. The user is not
// authenticated and retrying won't help until they log in.
if (debug) console.warn('[ws] auth preflight rejected (4xx), not opening WebSocket');
failureStore.set({
kind: 'auth-preflight',
class: 'AUTH',
status: result.status,
reason: result.reason
});
statusStore.set('failed');
terminalClosed = true;
permaClosedStore.set(true);
return;
}
if (result.outcome === 'transient') {
// Network error or 5xx. Retry via the normal backoff loop so
// the preflight automatically re-runs on the next attempt.
if (debug) console.warn('[ws] auth preflight transient failure, scheduling reconnect');
failureStore.set({
kind: 'auth-preflight',
class: 'AUTH',
status: result.status,
reason: result.reason
});
statusStore.set('disconnected');
scheduleReconnect();
return;
}
openSocket();
});
return;
}
openSocket();
}
function openSocket() {
try {
ws = new WebSocket(getUrl());
} catch {
scheduleReconnect();
return;
}
ws.onopen = () => {
attempt = 0;
lastServerMessage = Date.now();
failureStore.set(null);
setStatusOpen();
if (debug) console.log('[ws] connected');
// Advertise client capabilities. Server stores these on the
// connection's userData and uses them to gate opt-in wire
// features (currently: 'batch' for platform.publishBatched
// frames). Old servers ignore the unknown frame type.
ws?.send('{"type":"hello","caps":["batch"]}');
// If we have a previous session id and any tracked seqs, ask the