-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms-full.txt
More file actions
2056 lines (1643 loc) · 63.9 KB
/
llms-full.txt
File metadata and controls
2056 lines (1643 loc) · 63.9 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
# @fluxstack/live — Complete API Reference
> Real-time server-client state synchronization framework for TypeScript.
> Server components with reactive state, actions, rooms, auth, file uploads, and binary deltas.
---
## Table of Contents
1. [Architecture Overview](#architecture-overview)
2. [Package Structure](#package-structure)
3. [@fluxstack/live (Core)](#core-package)
- [LiveServer](#liveserver)
- [LiveComponent](#livecomponent)
- [Component Registry](#component-registry)
- [Protocol & Messages](#protocol--messages)
- [Transport Layer](#transport-layer)
- [Room System](#room-system)
- [Auth System](#auth-system)
- [Security](#security)
- [Connection Management](#connection-management)
- [File Upload](#file-upload)
- [Debug & Logging](#debug--logging)
- [Performance Monitoring](#performance-monitoring)
- [Build Plugin](#build-plugin)
- [Type Utilities](#type-utilities)
4. [@fluxstack/live-client (Browser Client)](#client-package)
- [LiveConnection](#liveconnection)
- [LiveComponentHandle](#livecomponenthandle)
- [useLive (Vanilla JS)](#uselive-vanilla-js)
- [RoomManager (Client)](#roommanager-client)
- [File Upload (Client)](#file-upload-client)
- [State Persistence](#state-persistence)
- [State Validator](#state-validator)
5. [@fluxstack/live-react (React Bindings)](#react-package)
- [LiveComponentsProvider](#livecomponentsprovider)
- [Live.use()](#liveuse)
- [useLiveComponent](#uselivecomponent)
- [useChunkedUpload](#usechunkedupload)
- [useLiveDebugger](#uselivedebugger)
6. [@fluxstack/live-elysia (Elysia Adapter)](#elysia-adapter)
7. [@fluxstack/live-express (Express Adapter)](#express-adapter)
8. [@fluxstack/live-fastify (Fastify Adapter)](#fastify-adapter)
9. [@fluxstack/live-redis (Redis Adapter)](#redis-adapter)
10. [Usage Examples](#usage-examples)
---
## Architecture Overview
```
Browser Server
┌──────────────────┐ ┌─────────────────────────────────┐
│ @fluxstack/ │ WebSocket │ @fluxstack/live │
│ live-react │◄───────────►│ LiveServer │
│ Live.use() │ JSON/Binary│ ├─ ComponentRegistry │
│ useLiveComponent│ │ ├─ LiveRoomManager │
│ │ │ ├─ LiveAuthManager │
│ @fluxstack/ │ │ ├─ StateSignatureManager │
│ live-client │ │ ├─ PerformanceMonitor │
│ LiveConnection │ │ └─ FileUploadManager │
│ LiveComponentHandle │ │
│ RoomManager │ │ Transport Adapters: │
└──────────────────┘ │ @fluxstack/live-elysia │
│ @fluxstack/live-express │
│ @fluxstack/live-fastify │
│ │
│ Optional: │
│ @fluxstack/live-redis │
└─────────────────────────────────┘
```
**Data flow:**
1. Client calls `Live.use(Counter)` — sends `COMPONENT_MOUNT` message via WebSocket
2. Server instantiates `Counter` LiveComponent, returns initial state + signed state
3. Client receives state, renders UI
4. Client calls `counter.$call('increment')` — sends `CALL_ACTION` message
5. Server executes action, calls `this.setState()` — sends `STATE_DELTA` to all connected clients
6. Client receives delta, merges into state, React re-renders
---
## Package Structure
```
fluxstack-live/
├── packages/
│ ├── core/ # @fluxstack/live — server framework
│ │ └── src/
│ │ ├── server/ LiveServer.ts
│ │ ├── component/ LiveComponent.ts, ComponentRegistry.ts, context.ts, types.ts
│ │ │ └── managers/ ComponentMessaging, ComponentStateManager,
│ │ │ ActionSecurityManager, ComponentRoomProxy
│ │ ├── protocol/ messages.ts, constants.ts, binary.ts
│ │ ├── transport/ types.ts, WsSendBatcher.ts
│ │ ├── rooms/ RoomEventBus.ts, RoomStateManager.ts,
│ │ │ LiveRoomManager.ts, adapters.ts, InMemoryRoomAdapter.ts
│ │ ├── auth/ types.ts, LiveAuthManager.ts, LiveAuthContext.ts
│ │ ├── security/ StateSignature.ts, sanitize.ts
│ │ ├── connection/ WebSocketConnectionManager.ts, RateLimiter.ts
│ │ ├── upload/ FileUploadManager.ts
│ │ ├── debug/ LiveDebugger.ts, LiveLogger.ts
│ │ ├── monitoring/ PerformanceMonitor.ts
│ │ └── build/ index.ts (Vite plugin)
│ ├── client/ # @fluxstack/live-client — browser client
│ │ └── src/ connection.ts, component.ts, rooms.ts, upload.ts,
│ │ persistence.ts, state-validator.ts, index.ts
│ ├── react/ # @fluxstack/live-react — React hooks
│ │ └── src/
│ │ ├── hooks/ useLiveComponent.ts, useChunkedUpload.ts,
│ │ │ useLiveChunkedUpload.ts, useLiveDebugger.ts
│ │ ├── components/ Live.tsx
│ │ └── LiveComponentsProvider.tsx
│ ├── elysia/ # @fluxstack/live-elysia
│ ├── express/ # @fluxstack/live-express
│ ├── fastify/ # @fluxstack/live-fastify
│ └── redis/ # @fluxstack/live-redis
```
---
## Core Package
### LiveServer
Main entry point. Orchestrates all subsystems and handles WebSocket lifecycle.
```typescript
import { LiveServer } from '@fluxstack/live'
interface LiveServerOptions {
/** Transport adapter (Elysia, Express, Fastify) */
transport: LiveTransport
/** WebSocket endpoint path. Default: '/api/live/ws' */
wsPath?: string
/** Enable debug mode. Default: false */
debug?: boolean
/** State signature configuration */
stateSignature?: StateSignatureConfig
/** Performance monitor configuration */
performance?: PerformanceConfig
/** File upload configuration */
fileUpload?: FileUploadConfig
/** Connection manager configuration */
connection?: Partial<ConnectionConfig>
/** Rate limiter: max tokens per connection */
rateLimitMaxTokens?: number
/** Rate limiter: tokens refilled per second */
rateLimitRefillRate?: number
/** Components path for auto-discovery */
componentsPath?: string
/** HTTP monitoring routes prefix. Set to false to disable. Default: '/api/live' */
httpPrefix?: string | false
/** Allowed origins for CSRF protection.
* When set, connections from unlisted origins are rejected.
* Example: ['https://myapp.com', 'http://localhost:3000'] */
allowedOrigins?: string[]
/** Cross-instance pub/sub adapter for horizontal scaling (e.g. Redis).
* Without this, rooms are local to the current instance. */
roomPubSub?: IRoomPubSubAdapter
}
class LiveServer {
// Public subsystem singletons
readonly roomEvents: RoomEventBus
readonly roomManager: LiveRoomManager
readonly debugger: LiveDebugger
readonly authManager: LiveAuthManager
readonly stateSignature: StateSignatureManager
readonly performanceMonitor: PerformanceMonitor
readonly fileUploadManager: FileUploadManager
readonly connectionManager: WebSocketConnectionManager
readonly registry: ComponentRegistry
readonly rateLimiter: RateLimiterRegistry
constructor(options: LiveServerOptions)
/** Register an auth provider */
useAuth(provider: LiveAuthProvider): this
/** Start: register WS + HTTP handlers on the transport */
async start(): Promise<void>
/** Graceful shutdown */
async shutdown(): Promise<void>
}
```
**HTTP monitoring routes** (when `httpPrefix` is not `false`):
- `GET /api/live/stats` — system statistics (components, rooms, connections, uploads, performance)
- `GET /api/live/components` — list registered component names
- `POST /api/live/rooms/:roomId/messages` — send message to room via HTTP
- `POST /api/live/rooms/:roomId/emit` — emit custom event to room via HTTP
---
### LiveComponent
Abstract base class for all server-side live components.
```typescript
import { LiveComponent } from '@fluxstack/live'
abstract class LiveComponent<
TState = ComponentState,
TPrivate extends Record<string, any> = Record<string, any>
> {
// ===== Static Configuration =====
/** Unique component name used for client-server mapping */
static componentName: string
/** Default initial state for new instances */
static defaultState: any
/** List of action methods callable from the client */
static publicActions?: readonly string[]
/** Component-level auth requirements */
static auth?: LiveComponentAuth
/** Per-action auth requirements */
static actionAuth?: LiveActionAuthMap
/** Zod schemas for action payload validation */
static actionSchemas?: Record<string, { safeParse: (data: unknown) => { success: boolean; error?: any; data?: any } }>
/** Rate limiting for actions */
static actionRateLimit?: { maxCalls: number; windowMs: number; perAction?: boolean }
/** Persistent state configuration (survives reconnects) */
static persistent?: Record<string, any>
/** Singleton mode — only one instance per component name */
static singleton?: boolean
/** Logging configuration */
static logging?: boolean | readonly ('lifecycle' | 'messages' | 'state' | 'performance' | 'rooms' | 'websocket')[]
// ===== Instance Properties =====
/** Unique instance ID (auto-generated) */
readonly id: string
/** Reactive state — changes are automatically synced to clients */
state: TState
/** WebSocket connection */
protected ws: GenericWebSocket
/** Room this component belongs to */
room?: string
/** User ID associated with this component */
userId?: string
/** Function to broadcast to room members */
broadcastToRoom: (message: BroadcastMessage) => void
constructor(initialState: Partial<TState>, ws: GenericWebSocket, options?: { room?: string; userId?: string })
// ===== Properties =====
/** Server-only private state (never sent to clients) */
get $private(): TPrivate
/** Room proxy — access rooms: this.$room.join(), this.$room.emit(), this.$room('roomId') */
get $room(): ServerRoomProxy
/** List of rooms this component has joined */
get $rooms(): string[]
/** Auth context for the current user */
get $auth(): LiveAuthContext
/** Persistent state (survives reconnects) */
get $persistent(): Record<string, any>
// ===== Lifecycle Hooks =====
/** Called when WebSocket connection opens */
protected onConnect(): void
/** Called after component is mounted. Can be async. */
protected onMount(): void | Promise<void>
/** Called when WebSocket connection closes */
protected onDisconnect(): void
/** Called when component is destroyed */
protected onDestroy(): void
/** Called after state changes */
protected onStateChange(changes: Partial<TState>): void
/** Called when component joins a room */
protected onRoomJoin(roomId: string): void
/** Called when component leaves a room */
protected onRoomLeave(roomId: string): void
/** Called during rehydration (reconnect with signed state) */
protected onRehydrate(previousState: TState): void
/** Called before an action executes. Return false to block it. */
protected onAction(action: string, payload: any): void | false | Promise<void | false>
/** Called when another client joins a singleton component */
protected onClientJoin(connectionId: string, connectionCount: number): void
/** Called when a client leaves a singleton component */
protected onClientLeave(connectionId: string, connectionCount: number): void
// ===== State Management =====
/** Update state and push delta to all connected clients */
setState(updates: Partial<TState> | ((prev: TState) => Partial<TState>)): void
/** Send binary state delta for high-frequency updates (games, real-time viz) */
sendBinaryDelta(delta: Partial<TState>, encoder: (delta: Partial<TState>) => Uint8Array): void
/** Set a single state value (called by client SET_VALUE messages) */
setValue<K extends keyof TState>(payload: { key: K; value: TState[K] }): { success: true; key: K; value: TState[K] }
/** Execute an action with security validation */
async executeAction(action: string, payload: any): Promise<any>
// ===== Messaging =====
/** Emit message to this component's client */
protected emit(type: string, payload: any): void
/** Broadcast message to all clients in the same room */
protected broadcast(type: string, payload: any, excludeCurrentUser?: boolean): void
// ===== Room Events =====
/** Emit event to all members in the current room */
protected emitRoomEvent(event: string, data: any, notifySelf?: boolean): number
/** Listen for room events */
protected onRoomEvent<T = any>(event: string, handler: (data: T) => void): void
/** Emit room event AND update state atomically */
protected emitRoomEventWithState(event: string, data: any, stateUpdates: Partial<TState>): number
/** Subscribe this component to a specific room */
protected subscribeToRoom(roomId: string): void
/** Unsubscribe from the current room */
protected unsubscribeFromRoom(): void
// ===== Cleanup =====
/** Destroy component and clean up resources */
destroy(): void
/** Get state safe for serialization */
getSerializableState(): TState
/** Set auth context */
setAuthContext(context: LiveAuthContext): void
}
```
**State direct accessors:** If `defaultState` defines properties, they become directly accessible on the component instance. For example, if `defaultState = { count: 0 }`, then `this.count` is a getter/setter for `this.state.count`. Setting `this.count = 5` automatically calls `setState({ count: 5 })`.
**Reactive proxy state:** `this.state` is a Proxy. Assigning to `this.state.count = 5` inside a method automatically emits a `STATE_DELTA` to clients. Multiple assignments within the same synchronous execution are batched.
---
### Component Registry
Manages component registration, lifecycle, mounting, and message routing.
```typescript
class ComponentRegistry {
constructor(deps: {
authManager: LiveAuthManager
debugger: LiveDebugger
stateSignature: StateSignatureManager
performanceMonitor: PerformanceMonitor
})
/** Register a component definition (name + class) */
registerComponent<TState>(definition: ComponentDefinition<TState>): void
/** Register a component class directly */
registerComponentClass(
name: string,
componentClass: new (initialState: any, ws: GenericWebSocket, options?: { room?: string; userId?: string }) => LiveComponent<any>,
): void
/** Auto-discover components from a directory (scans for files exporting LiveComponent subclasses) */
async autoDiscoverComponents(componentsPath: string): Promise<void>
/** Mount a component: create instance, return initial state + signed state */
async mountComponent(
ws: GenericWebSocket,
componentName: string,
props?: Record<string, unknown>,
options?: { room?: string; userId?: string; version?: string; debugLabel?: string },
): Promise<{ componentId: string; initialState: unknown; signedState: unknown }>
/** Rehydrate a component from signed state (reconnection) */
async rehydrateComponent(
componentId: string,
componentName: string,
signedState: SignedState,
ws: GenericWebSocket,
options?: { room?: string; userId?: string },
): Promise<{ success: boolean; newComponentId?: string; error?: string }>
/** Unmount and destroy a component */
unmountComponent(componentId: string, ws?: GenericWebSocket): void
/** Execute an action on a mounted component */
async executeAction(componentId: string, action: string, payload: any): Promise<any>
/** Handle incoming WebSocket message (routes to appropriate component) */
async handleMessage(ws: GenericWebSocket, message: LiveMessage): Promise<{
success: boolean; result?: unknown; error?: string
} | null>
/** Clean up all components for a disconnected WebSocket */
cleanupConnection(ws: GenericWebSocket): void
/** Get system statistics */
getStats(): {
components: number
definitions: number
rooms: number
connections: number
singletons: Record<string, any>
roomDetails: Record<string, number>
}
/** Get registered component names */
getRegisteredComponentNames(): string[]
/** Get a component instance by ID */
getComponent(componentId: string): LiveComponent | undefined
/** Clean up all components */
cleanup(): void
}
```
---
### Protocol & Messages
#### Constants
```typescript
const PROTOCOL_VERSION = 1
const DEFAULT_WS_PATH = '/api/live/ws'
const DEFAULT_CHUNK_SIZE = 64 * 1024 // 64 KB
const MAX_MESSAGE_SIZE = 100 * 1024 * 1024 // 100 MB
const MAX_ROOM_STATE_SIZE = 10 * 1024 * 1024 // 10 MB
const MAX_ROOMS_PER_CONNECTION = 50
const MAX_ROOM_NAME_LENGTH = 64
const ROOM_NAME_REGEX = /^[a-zA-Z0-9_:.-]{1,64}$/
const MAX_QUEUE_SIZE = 1000
const DEFAULT_NONCE_TTL = 5 * 60 * 1000 // 5 minutes
const DEFAULT_RATE_LIMIT_MAX_TOKENS = 100
const DEFAULT_RATE_LIMIT_REFILL_RATE = 50
```
#### Client-to-Server Messages (LiveMessage)
```typescript
interface LiveMessage {
type:
| 'COMPONENT_MOUNT' // Mount a component
| 'COMPONENT_UNMOUNT' // Unmount a component
| 'COMPONENT_REHYDRATE' // Rehydrate from signed state
| 'CALL_ACTION' // Call a server action
| 'PROPERTY_UPDATE' // Update a property
| 'STATE_UPDATE' // Full state update
| 'AUTH' // Authenticate
| 'ROOM_JOIN' // Join a room
| 'ROOM_LEAVE' // Leave a room
| 'ROOM_EMIT' // Emit event to room
| 'ROOM_STATE_SET' // Update room state
| 'ROOM_STATE_GET' // Get room state
| 'FILE_UPLOAD_START' // Start file upload
| 'FILE_UPLOAD_CHUNK' // Send file chunk
| 'FILE_UPLOAD_COMPLETE' // Complete file upload
| 'COMPONENT_PING' // Heartbeat ping
componentId: string
action?: string
property?: string
payload?: any
timestamp?: number
userId?: string
room?: string
requestId?: string // For request-response pattern
responseId?: string
expectResponse?: boolean // Set to false for fire-and-forget
}
```
#### Server-to-Client Messages (WebSocketResponse)
```typescript
interface WebSocketResponse {
type:
| 'CONNECTION_ESTABLISHED' // Connection ready
| 'MESSAGE_RESPONSE' // Generic response
| 'ACTION_RESPONSE' // Action result
| 'COMPONENT_MOUNTED' // Mount confirmation
| 'COMPONENT_REHYDRATED' // Rehydration confirmation
| 'STATE_UPDATE' // Full state push
| 'STATE_DELTA' // Partial state push
| 'BROADCAST' // Broadcast to room
| 'ERROR' // Error message
| 'AUTH_RESPONSE' // Auth result
| 'ROOM_EVENT' // Room event
| 'ROOM_STATE' // Room state update
| 'ROOM_SYSTEM' // Room system event ($sub:join, $sub:leave)
| 'ROOM_JOINED' // Room join confirmation
| 'ROOM_LEFT' // Room leave confirmation
| 'FILE_UPLOAD_PROGRESS' // Upload progress
| 'FILE_UPLOAD_COMPLETE' // Upload complete
| 'FILE_UPLOAD_START_RESPONSE' // Upload start confirmation
| 'COMPONENT_PONG' // Heartbeat pong
originalType?: string
componentId?: string
success?: boolean
result?: any
error?: string
requestId?: string
timestamp?: number
connectionId?: string
payload?: any
signedState?: any
}
```
#### Binary Protocol
For high-frequency state updates (games, real-time data viz):
```typescript
// BINARY_STATE_DELTA frame format:
// [0x01] [componentId length: 1 byte] [componentId: N bytes] [payload: remaining bytes]
function encodeBinaryChunk(header: BinaryChunkHeader, data: Buffer | Uint8Array): Buffer
function decodeBinaryChunk(raw: ArrayBuffer | Uint8Array): { header: BinaryChunkHeader; data: Buffer }
```
#### WsSendBatcher
Batches and optimizes WebSocket sends:
```typescript
/** Queue a message to be sent (batched with other messages in the same tick) */
function queueWsMessage(ws: GenericWebSocket, message: PendingMessage): void
/** Queue a pre-serialized JSON string */
function queuePreSerialized(ws: GenericWebSocket, serialized: string): void
/** Send immediately without batching (for responses) */
function sendImmediate(ws: GenericWebSocket, data: string): void
```
---
### Transport Layer
Transport adapters implement this interface to bridge different web frameworks:
```typescript
interface LiveTransport {
/** Register WebSocket handler */
registerWebSocket(config: WebSocketConfig): void | Promise<void>
/** Register HTTP routes */
registerHttpRoutes(routes: HttpRouteDefinition[]): void | Promise<void>
/** Optional startup hook */
start?(): void | Promise<void>
/** Optional shutdown hook */
shutdown?(): void | Promise<void>
}
interface WebSocketConfig {
path: string
onOpen(ws: GenericWebSocket): void | Promise<void>
onMessage(ws: GenericWebSocket, message: unknown, isBinary: boolean): void | Promise<void>
onClose(ws: GenericWebSocket, code: number, reason: string): void | Promise<void>
onError?(ws: GenericWebSocket, error: Error): void
}
interface GenericWebSocket {
send(data: string | ArrayBuffer | Uint8Array, compress?: boolean): void | number
close(code?: number, reason?: string): void
data: LiveWSData
readonly remoteAddress: string
readonly readyState: 0 | 1 | 2 | 3
}
interface LiveWSData {
connectionId: string
components: Map<string, any>
subscriptions: Set<string>
connectedAt: Date
userId?: string
authContext?: LiveAuthContext
rooms?: Set<string>
origin?: string
}
interface HttpRouteDefinition {
method: 'GET' | 'POST' | 'PUT' | 'DELETE'
path: string
handler: (request: HttpRequest) => HttpResponse | Promise<HttpResponse>
metadata?: { summary?: string; description?: string; tags?: string[] }
}
interface HttpRequest {
params: Record<string, string>
query: Record<string, string | undefined>
body: unknown
headers: Record<string, string | undefined>
}
interface HttpResponse {
status?: number
body: unknown
headers?: Record<string, string>
}
```
---
### Room System
#### RoomEventBus
Server-side pub/sub event bus for room events:
```typescript
class RoomEventBus {
/** Subscribe to events on a room */
on(roomType: string, roomId: string, event: string, componentId: string, handler: EventHandler): () => void
/** Emit event to all subscribers in a room */
emit(roomType: string, roomId: string, event: string, data: any, excludeComponentId?: string): number
/** Unsubscribe all handlers for a component */
unsubscribeAll(componentId: string): number
/** Clear all handlers for a room */
clearRoom(roomType: string, roomId: string): number
/** Get subscription statistics */
getStats(): { totalSubscriptions: number; rooms: Record<string, { events: Record<string, number> }> }
}
/** Create a typed event bus for compile-time safety */
function createTypedRoomEventBus<TRoomEvents extends Record<string, Record<string, any>>>(): TypedRoomEventBus
```
#### RoomStateManager
Server-side room state storage:
```typescript
class RoomStateManager {
get<T extends RoomStateData>(roomId: string, defaultState?: T): T
update<T extends RoomStateData>(roomId: string, updates: Partial<T>): T
set<T extends RoomStateData>(roomId: string, state: T): void
join(roomId: string): void
leave(roomId: string): void
has(roomId: string): boolean
delete(roomId: string): boolean
getStats(): { totalRooms: number; rooms: Record<string, { componentCount: number; stateKeys: string[] }> }
}
/** Create a typed room state manager */
function createTypedRoomState<TRoomTypes extends Record<string, RoomStateData>>(): TypedRoomStateManager
```
#### LiveRoomManager
High-level room manager used by LiveServer. Manages room membership, state, and WebSocket broadcasting:
```typescript
class LiveRoomManager {
constructor(roomEvents: RoomEventBus, pubsub?: IRoomPubSubAdapter)
/** Component joins a room. Creates room if it doesn't exist. */
joinRoom<TState = any>(componentId: string, roomId: string, ws: GenericWebSocket, initialState?: TState): { state: TState }
/** Component leaves a room. Empty rooms are cleaned up after 5 minutes. */
leaveRoom(componentId: string, roomId: string): void
/** Component disconnects — leave all rooms with batched notifications. */
cleanupComponent(componentId: string): void
/** Emit event to all room members via WebSocket + RoomEventBus + pub/sub */
emitToRoom(roomId: string, event: string, data: any, excludeComponentId?: string): number
/** Update room state (merge). Broadcasts to members. Enforces MAX_ROOM_STATE_SIZE. */
setRoomState(roomId: string, updates: any, excludeComponentId?: string): void
/** Get room state */
getRoomState<TState = any>(roomId: string): TState
/** Check if component is in a room */
isInRoom(componentId: string, roomId: string): boolean
/** Get list of rooms for a component */
getComponentRooms(componentId: string): string[]
/** Get room statistics */
getStats(): { totalRooms: number; rooms: Record<string, { members: number; createdAt: number; lastActivity: number }> }
}
```
#### Room Adapters
Pluggable interfaces for room storage and cross-instance pub/sub:
```typescript
/** Adapter for room state storage */
interface IRoomStorageAdapter {
getOrCreateRoom(roomId: string, initialState?: any): Promise<{ state: any; created: boolean }>
getState(roomId: string): Promise<any>
updateState(roomId: string, updates: any): Promise<void>
hasRoom(roomId: string): Promise<boolean>
deleteRoom(roomId: string): Promise<boolean>
getStats(): Promise<{ totalRooms: number; rooms: Record<string, any> }>
}
/** Adapter for cross-instance pub/sub (horizontal scaling) */
interface IRoomPubSubAdapter {
publish(roomId: string, event: string, data: any): Promise<void>
subscribe(roomId: string, handler: (event: string, data: any) => void): Promise<() => void>
publishMembership(roomId: string, action: 'join' | 'leave', componentId: string): Promise<void>
publishStateChange(roomId: string, updates: any): Promise<void>
}
/** Default in-memory adapter (single-instance, no external dependencies) */
class InMemoryRoomAdapter implements IRoomStorageAdapter, IRoomPubSubAdapter {
// All pub/sub methods are no-ops (single-instance mode)
}
```
---
### Auth System
#### Types
```typescript
interface LiveAuthCredentials {
token?: string
publicKey?: string
signature?: string
timestamp?: number
nonce?: string
[key: string]: unknown
}
interface LiveAuthUser {
id: string
roles?: string[]
permissions?: string[]
[key: string]: unknown
}
interface LiveAuthContext {
readonly authenticated: boolean
readonly user?: LiveAuthUser
readonly token?: string
readonly authenticatedAt?: number
hasRole(role: string): boolean
hasAnyRole(roles: string[]): boolean
hasAllRoles(roles: string[]): boolean
hasPermission(permission: string): boolean
hasAllPermissions(permissions: string[]): boolean
hasAnyPermission(permissions: string[]): boolean
}
interface LiveAuthProvider {
readonly name: string
authenticate(credentials: LiveAuthCredentials): Promise<LiveAuthContext | null>
authorizeAction?(context: LiveAuthContext, componentName: string, action: string): Promise<boolean>
authorizeRoom?(context: LiveAuthContext, roomId: string): Promise<boolean>
}
interface LiveComponentAuth {
required?: boolean
roles?: string[]
permissions?: string[]
}
interface LiveActionAuth {
roles?: string[]
permissions?: string[]
}
type LiveActionAuthMap = Record<string, LiveActionAuth>
```
#### LiveAuthManager
```typescript
class LiveAuthManager {
/** Register an auth provider */
register(provider: LiveAuthProvider): void
/** Unregister by name */
unregister(name: string): void
/** Set default provider */
setDefault(name: string): void
/** Authenticate credentials */
async authenticate(credentials: LiveAuthCredentials, providerName?: string): Promise<LiveAuthContext>
/** Check component-level authorization */
authorizeComponent(authContext: LiveAuthContext, authConfig: LiveComponentAuth | undefined): LiveAuthResult
/** Check action-level authorization */
async authorizeAction(
authContext: LiveAuthContext,
componentName: string,
action: string,
actionAuth: LiveActionAuth | undefined,
providerName?: string,
): Promise<LiveAuthResult>
}
```
#### Auth Contexts
```typescript
/** Authenticated user context */
class AuthenticatedContext implements LiveAuthContext {
readonly authenticated = true
constructor(user: LiveAuthUser, token?: string)
}
/** Anonymous (unauthenticated) context */
class AnonymousContext implements LiveAuthContext {
readonly authenticated = false
// All has* methods return false
}
const ANONYMOUS_CONTEXT: AnonymousContext
```
---
### Security
#### StateSignatureManager
HMAC-SHA256 state signing with optional encryption, compression, and nonce-based replay protection:
```typescript
interface StateSignatureConfig {
secret?: string
rotationEnabled?: boolean
rotationInterval?: number
compressionEnabled?: boolean
encryptionEnabled?: boolean
nonceEnabled?: boolean
maxStateAge?: number
backupEnabled?: boolean
maxBackups?: number
nonceTTL?: number
}
interface SignedState {
data: string
signature: string
timestamp: number
version: number
componentId: string
nonce?: string
compressed?: boolean
encrypted?: boolean
}
class StateSignatureManager {
constructor(config?: StateSignatureConfig)
/** Sign component state */
signState(
componentId: string,
state: Record<string, unknown>,
version: number,
options?: { compress?: boolean; backup?: boolean },
): SignedState
/** Validate a signed state (checks HMAC, nonce, age) */
validateState(signedState: SignedState, options?: { skipNonce?: boolean }): { valid: boolean; error?: string }
/** Extract data from signed state */
extractData(signedState: SignedState): Record<string, unknown>
/** Get state backups for a component */
getBackups(componentId: string): SignedState[]
/** Graceful shutdown (clear timers) */
shutdown(): void
}
```
#### Payload Sanitization
Strips prototype pollution keys (`__proto__`, `constructor`, `prototype`) from incoming payloads:
```typescript
function sanitizePayload<T>(value: T, depth?: number): T
```
---
### Connection Management
```typescript
interface ConnectionConfig {
maxConnections: number
connectionTimeout: number
heartbeatInterval: number
reconnectAttempts: number
reconnectDelay: number
maxReconnectDelay: number
jitterFactor: number
loadBalancing: 'round-robin' | 'least-connections' | 'random'
healthCheckInterval: number
messageQueueSize: number
offlineQueueEnabled: boolean
}
class WebSocketConnectionManager extends EventEmitter {
constructor(config?: Partial<ConnectionConfig>)
registerConnection(ws: GenericWebSocket, connectionId: string, poolId?: string): void
cleanupConnection(connectionId: string): void
getConnectionMetrics(connectionId: string): ConnectionMetrics | null
getAllConnectionMetrics(): ConnectionMetrics[]
getSystemStats(): {
totalConnections: number
activeConnections: number
totalPools: number
totalQueuedMessages: number
maxConnections: number
connectionUtilization: number
}
shutdown(): void
}
```
#### Rate Limiter
Token-bucket rate limiter per connection:
```typescript
class ConnectionRateLimiter {
constructor(maxTokens?: number, refillRate?: number)
/** Returns true if request is allowed, false if rate-limited */
tryConsume(count?: number): boolean
}
class RateLimiterRegistry {
constructor(maxTokens?: number, refillRate?: number)
/** Get or create rate limiter for a connection */
get(connectionId: string): ConnectionRateLimiter
/** Remove rate limiter for a disconnected connection */
remove(connectionId: string): void
}
```
---
### File Upload
Chunked file upload system with per-user quotas and type validation:
```typescript
interface FileUploadConfig {
maxUploadSize?: number // Default: 50 MB
chunkTimeout?: number // Default: 30s
maxBytesPerUser?: number // Per-user upload quota
quotaResetInterval?: number // Quota reset interval
allowedTypes?: string[] // Allowed MIME types (e.g. ['image/png', 'image/jpeg'])
blockedExtensions?: string[] // Blocked file extensions
uploadsDir?: string // Upload directory
assembleFile?: (upload: ActiveUpload) => Promise<string> // Custom file assembly
}
class FileUploadManager {
constructor(config?: FileUploadConfig)
async startUpload(message: FileUploadStartMessage, userId?: string): Promise<{ success: boolean; error?: string }>
async receiveChunk(message: FileUploadChunkMessage, binaryData?: Buffer | null): Promise<FileUploadProgressResponse | null>
async completeUpload(message: FileUploadCompleteMessage): Promise<FileUploadCompleteResponse>
getUserUploadUsage(userId: string): { used: number; limit: number; remaining: number }
getUploadStatus(uploadId: string): ActiveUpload | null
getStats(): { activeUploads: number; maxUploadSize: number; allowedTypes: string[] }
shutdown(): void
}
```
---
### Debug & Logging
#### LiveDebugger
Full debug system with event tracking, component snapshots, and WebSocket debug clients:
```typescript