@panyam/servicekit-client 0.0.4

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 panyam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,385 @@
1
+ # @panyam/servicekit-client
2
+
3
+ TypeScript client library for [ServiceKit](https://github.com/panyam/servicekit) WebSocket protocols.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @panyam/servicekit-client
9
+ ```
10
+
11
+ ## Architecture
12
+
13
+ The client mirrors the server-side architecture with clear separation of concerns:
14
+
15
+ ```
16
+ ┌─────────────────────────────────────────────────────────────┐
17
+ │ Transport Layer │
18
+ │ • WebSocket connection management │
19
+ │ • Ping/Pong heartbeats (always JSON) │
20
+ │ • Error messages (always JSON) │
21
+ └─────────────────────────────────────────────────────────────┘
22
+ │
23
+ ▼
24
+ ┌─────────────────────────────────────────────────────────────┐
25
+ │ Codec Layer │
26
+ │ • Data message encoding/decoding │
27
+ │ • JSONCodec (default) - matches server JSONCodec │
28
+ │ • BinaryCodec - matches server BinaryProtoCodec │
29
+ └─────────────────────────────────────────────────────────────┘
30
+ ```
31
+
32
+ **Key principle**: Control messages (ping/pong/error) are **always JSON text frames** at the transport layer, regardless of what codec is used for data messages. This ensures clients can always communicate even when using binary protocols.
33
+
34
+ ## Clients
35
+
36
+ | Client | Use Case | Protocol |
37
+ |--------|----------|----------|
38
+ | `BaseWSClient` | Low-level WebSocket with auto ping/pong | Configurable codec |
39
+ | `GRPCWSClient` | gRPC-style streaming | Envelope: `{type: "data", data: ...}` |
40
+ | `TypedGRPCWSClient<TIn, TOut>` | Type-safe wrapper for GRPCWSClient | Same as GRPCWSClient |
41
+
42
+ ## Codecs
43
+
44
+ | Codec | Server Codec | Wire Format |
45
+ |-------|--------------|-------------|
46
+ | `JSONCodec` (default) | `JSONCodec`, `TypedJSONCodec` | JSON text |
47
+ | `BinaryCodec` | `BinaryProtoCodec` | Binary protobuf |
48
+
49
+ **Important**: Client and server must use matching codecs!
50
+
51
+ ## Quick Start
52
+
53
+ ### Basic WebSocket (http/JSONConn)
54
+
55
+ Use `BaseWSClient` for plain WebSocket connections with automatic ping/pong handling:
56
+
57
+ ```typescript
58
+ import { BaseWSClient } from '@panyam/servicekit-client';
59
+
60
+ const client = new BaseWSClient();
61
+
62
+ client.onMessage = (data) => {
63
+ console.log('Received:', data);
64
+ };
65
+
66
+ client.onClose = () => {
67
+ console.log('Disconnected');
68
+ };
69
+
70
+ await client.connect('ws://localhost:8080/ws');
71
+ client.send({ hello: 'world' });
72
+ ```
73
+
74
+ ### gRPC-WebSocket Streaming (grpcws)
75
+
76
+ Use `GRPCWSClient` for gRPC-style streaming with the envelope protocol:
77
+
78
+ ```typescript
79
+ import { GRPCWSClient } from '@panyam/servicekit-client';
80
+
81
+ const client = new GRPCWSClient();
82
+
83
+ client.onMessage = (data) => {
84
+ console.log('Event:', data);
85
+ };
86
+
87
+ client.onStreamEnd = () => {
88
+ console.log('Stream completed');
89
+ };
90
+
91
+ client.onError = (error) => {
92
+ console.error('Error:', error);
93
+ };
94
+
95
+ await client.connect('ws://localhost:8080/ws/v1/subscribe?game_id=123');
96
+ ```
97
+
98
+ ### Type-Safe with Protobuf Types
99
+
100
+ Use `TypedGRPCWSClient` with your protobuf-generated TypeScript types:
101
+
102
+ ```typescript
103
+ import { TypedGRPCWSClient } from '@panyam/servicekit-client';
104
+ import { PlayerAction, GameState } from './gen/game_pb';
105
+
106
+ const client = new TypedGRPCWSClient<PlayerAction, GameState>();
107
+
108
+ client.onMessage = (state: GameState) => {
109
+ console.log('Players:', state.players);
110
+ };
111
+
112
+ await client.connect('ws://localhost:8080/ws/v1/sync');
113
+ client.send({ actionId: '1', move: { x: 10, y: 20 } });
114
+ ```
115
+
116
+ ### Binary Protocol (BinaryProtoCodec)
117
+
118
+ For high-throughput scenarios using binary protobuf (matches server `BinaryProtoCodec`):
119
+
120
+ ```typescript
121
+ import { BaseWSClient, BinaryCodec } from '@panyam/servicekit-client';
122
+ import { MyRequest, MyResponse } from './gen/my_pb';
123
+
124
+ // Create a binary codec using your protobuf library's encode/decode functions
125
+ const codec = new BinaryCodec<MyResponse, MyRequest>(
126
+ // Decode: ArrayBuffer -> MyResponse
127
+ (data) => MyResponse.decode(new Uint8Array(data)),
128
+ // Encode: MyRequest -> Uint8Array
129
+ (msg) => MyRequest.encode(msg).finish()
130
+ );
131
+
132
+ const client = new BaseWSClient({ codec });
133
+
134
+ client.onMessage = (response: MyResponse) => {
135
+ console.log('Received:', response);
136
+ };
137
+
138
+ await client.connect('ws://localhost:8080/ws/binary');
139
+ client.send(MyRequest.create({ id: 1, action: 'test' }));
140
+ ```
141
+
142
+ **Note**: Even with binary data protocol, pings/pongs/errors are still JSON text frames. The transport layer handles this automatically.
143
+
144
+ ## Streaming Patterns
145
+
146
+ ### Server Streaming
147
+
148
+ Server sends multiple messages; client just listens:
149
+
150
+ ```typescript
151
+ const client = new GRPCWSClient();
152
+ client.onMessage = (event) => console.log('Event:', event);
153
+ client.onStreamEnd = () => console.log('Done');
154
+
155
+ await client.connect('ws://localhost:8080/ws/v1/subscribe');
156
+ // Just listen - server pushes events
157
+ ```
158
+
159
+ ### Client Streaming
160
+
161
+ Client sends multiple messages; server responds once at the end:
162
+
163
+ ```typescript
164
+ const client = new GRPCWSClient();
165
+ client.onMessage = (summary) => console.log('Result:', summary);
166
+
167
+ await client.connect('ws://localhost:8080/ws/v1/commands');
168
+
169
+ // Send multiple commands
170
+ client.send({ commandId: '1', commandType: 'move' });
171
+ client.send({ commandId: '2', commandType: 'attack' });
172
+
173
+ // Signal done sending - server will respond
174
+ client.endSend();
175
+ ```
176
+
177
+ ### Bidirectional Streaming
178
+
179
+ Both sides send messages concurrently:
180
+
181
+ ```typescript
182
+ const client = new GRPCWSClient();
183
+ client.onMessage = (state) => updateUI(state);
184
+
185
+ await client.connect('ws://localhost:8080/ws/v1/sync');
186
+
187
+ // Send actions whenever
188
+ client.send({ actionId: '1', move: { x: 10, y: 20 } });
189
+
190
+ // Receive responses concurrently
191
+ // When done sending:
192
+ client.endSend();
193
+ ```
194
+
195
+ ## API Reference
196
+
197
+ ### BaseWSClient
198
+
199
+ Low-level WebSocket client with automatic ping/pong and configurable codec.
200
+
201
+ ```typescript
202
+ class BaseWSClient<I = unknown, O = unknown> {
203
+ // Constructor
204
+ constructor(options?: {
205
+ autoPong?: boolean; // Auto-respond to pings (default: true)
206
+ WebSocket?: typeof WebSocket; // Custom WebSocket (for Node.js)
207
+ codec?: Codec<I, O>; // Codec for data messages (default: JSONCodec)
208
+ })
209
+
210
+ // Connection
211
+ connect(url: string): Promise<void>
212
+ close(): void
213
+
214
+ // Sending
215
+ send(data: O): void // Encoded via codec
216
+ sendRaw(message: string | ArrayBuffer): void // Bypass codec
217
+
218
+ // Events
219
+ onMessage: (data: I) => void
220
+ onPing: (pingId: number) => void
221
+ onClose: () => void
222
+ onError: (error: string) => void
223
+
224
+ // State
225
+ readonly codec: Codec<I, O>
226
+ readonly isConnected: boolean
227
+ readonly readyState: number
228
+ }
229
+ ```
230
+
231
+ ### Codec Interface
232
+
233
+ ```typescript
234
+ interface Codec<I, O> {
235
+ decode(data: string | ArrayBuffer): I;
236
+ encode(msg: O): string | ArrayBuffer;
237
+ }
238
+ ```
239
+
240
+ ### JSONCodec
241
+
242
+ Default codec for JSON text messages:
243
+
244
+ ```typescript
245
+ class JSONCodec<I = unknown, O = unknown> implements Codec<I, O> {
246
+ decode(data: string | ArrayBuffer): I; // JSON.parse
247
+ encode(msg: O): string; // JSON.stringify
248
+ }
249
+ ```
250
+
251
+ ### BinaryCodec
252
+
253
+ For binary protobuf messages:
254
+
255
+ ```typescript
256
+ class BinaryCodec<I, O> implements Codec<I, O> {
257
+ constructor(
258
+ decodeFunc: (data: ArrayBuffer) => I,
259
+ encodeFunc: (msg: O) => Uint8Array
260
+ );
261
+ decode(data: string | ArrayBuffer): I; // Calls decodeFunc
262
+ encode(msg: O): ArrayBuffer; // Calls encodeFunc
263
+ }
264
+ ```
265
+
266
+ ### GRPCWSClient
267
+
268
+ gRPC-WebSocket client with envelope protocol.
269
+
270
+ ```typescript
271
+ class GRPCWSClient {
272
+ // Connection
273
+ connect(url: string): Promise<void>
274
+ close(): void
275
+
276
+ // Sending (wrapped in {type: "data", data: ...})
277
+ send(data: unknown): void
278
+ endSend(): void // Half-close
279
+ cancel(): void // Cancel stream
280
+
281
+ // Events
282
+ onMessage: (data: unknown) => void
283
+ onStreamEnd: () => void
284
+ onError: (error: string) => void
285
+ onClose: () => void
286
+ onPing: (pingId: number) => void
287
+
288
+ // State
289
+ readonly isConnected: boolean
290
+ readonly readyState: number
291
+ }
292
+ ```
293
+
294
+ ### TypedGRPCWSClient<TIn, TOut>
295
+
296
+ Type-safe wrapper for GRPCWSClient.
297
+
298
+ ```typescript
299
+ class TypedGRPCWSClient<TIn, TOut> {
300
+ // Same API as GRPCWSClient, but with typed send/onMessage
301
+ send(data: TIn): void
302
+ onMessage: (data: TOut) => void
303
+ // ... other methods same as GRPCWSClient
304
+ }
305
+ ```
306
+
307
+ ## Protocol Details
308
+
309
+ ### Ping/Pong Heartbeat
310
+
311
+ Both clients automatically respond to server pings:
312
+ - Server sends: `{type: "ping", pingId: N}`
313
+ - Client responds: `{type: "pong", pingId: N}`
314
+
315
+ ### gRPC-WS Envelope Format
316
+
317
+ GRPCWSClient uses the following message envelope:
318
+
319
+ **Client → Server:**
320
+ ```json
321
+ {"type": "data", "data": <payload>}
322
+ {"type": "end_send"}
323
+ {"type": "cancel"}
324
+ ```
325
+
326
+ **Server → Client:**
327
+ ```json
328
+ {"type": "data", "data": <payload>}
329
+ {"type": "stream_end"}
330
+ {"type": "error", "error": "message"}
331
+ ```
332
+
333
+ ## Configuration
334
+
335
+ ### Custom WebSocket Implementation
336
+
337
+ For Node.js or testing, provide a custom WebSocket:
338
+
339
+ ```typescript
340
+ import WebSocket from 'ws';
341
+
342
+ const client = new GRPCWSClient({
343
+ WebSocket: WebSocket as any,
344
+ });
345
+ ```
346
+
347
+ ### Disable Auto Pong
348
+
349
+ ```typescript
350
+ const client = new BaseWSClient({
351
+ autoPong: false,
352
+ });
353
+
354
+ client.onPing = (pingId) => {
355
+ // Handle ping manually
356
+ client.send({ type: 'pong', pingId });
357
+ };
358
+ ```
359
+
360
+ ## Protobuf Type Generation
361
+
362
+ This client works with any TypeScript protoc plugin. Popular options:
363
+
364
+ - **[@bufbuild/protobuf](https://github.com/bufbuild/protobuf-es)** - Modern, tree-shakeable
365
+ - **[protobuf-ts](https://github.com/timostamm/protobuf-ts)** - Feature-rich
366
+ - **[ts-proto](https://github.com/stephenh/ts-proto)** - Plain TypeScript interfaces
367
+
368
+ Example with buf:
369
+
370
+ ```bash
371
+ buf generate
372
+ ```
373
+
374
+ Then use the generated types:
375
+
376
+ ```typescript
377
+ import { TypedGRPCWSClient } from '@panyam/servicekit-client';
378
+ import { PlayerAction, GameState } from './gen/game_pb';
379
+
380
+ const client = new TypedGRPCWSClient<PlayerAction, GameState>();
381
+ ```
382
+
383
+ ## License
384
+
385
+ MIT
@@ -0,0 +1,93 @@
1
+ /**
2
+ * BaseWSClient - Low-level WebSocket client with automatic ping/pong handling.
3
+ *
4
+ * This client handles the connection lifecycle and heartbeat mechanism.
5
+ * It sends and receives raw JSON messages without any envelope wrapping.
6
+ *
7
+ * Use this directly for http/JSONConn servers, or as the base for GRPCWSClient.
8
+ */
9
+ import { ClientOptions, Codec, MessageHandler, ErrorHandler, VoidHandler } from './types';
10
+ /**
11
+ * Base WebSocket client with automatic ping/pong heartbeat handling.
12
+ *
13
+ * Features:
14
+ * - Automatic ping/pong response (keeps connection alive)
15
+ * - Promise-based connect()
16
+ * - Event handlers for messages, errors, and close
17
+ * - Connection state tracking
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const client = new BaseWSClient();
22
+ * client.onMessage = (data) => console.log('Received:', data);
23
+ * client.onClose = () => console.log('Disconnected');
24
+ * await client.connect('ws://localhost:8080/ws');
25
+ * client.send({ hello: 'world' });
26
+ * ```
27
+ */
28
+ export declare class BaseWSClient<I = unknown, O = unknown> {
29
+ private ws;
30
+ private _codec;
31
+ private _autoPong;
32
+ private _WebSocket;
33
+ /** Called when a data message is received (decoded by codec) */
34
+ onMessage: MessageHandler<I>;
35
+ /** Called when a ping is received (after auto-pong if enabled) */
36
+ onPing: (pingId: number) => void;
37
+ /** Called when the connection closes */
38
+ onClose: VoidHandler;
39
+ /** Called when a WebSocket error occurs */
40
+ onError: ErrorHandler;
41
+ constructor(options?: ClientOptions<I, O>);
42
+ /** Get the codec used for encoding/decoding data messages */
43
+ get codec(): Codec<I, O>;
44
+ /**
45
+ * Connect to a WebSocket server.
46
+ * @param url The WebSocket URL to connect to
47
+ * @returns Promise that resolves when connected
48
+ */
49
+ connect(url: string): Promise<void>;
50
+ /**
51
+ * Send a data message to the server using the configured codec.
52
+ * @param data The data to send (will be encoded by codec)
53
+ */
54
+ send(data: O): void;
55
+ /**
56
+ * Send a raw message to the server (bypasses codec).
57
+ * Useful for control messages like pong.
58
+ * @param message The raw string or ArrayBuffer to send
59
+ */
60
+ sendRaw(message: string | ArrayBuffer): void;
61
+ /**
62
+ * Close the WebSocket connection.
63
+ */
64
+ close(): void;
65
+ /**
66
+ * Check if the client is connected.
67
+ */
68
+ get isConnected(): boolean;
69
+ /**
70
+ * Get the WebSocket ready state.
71
+ */
72
+ get readyState(): number;
73
+ /**
74
+ * Handle incoming raw message data.
75
+ * - Text frames: Check for control messages (ping), then decode with codec
76
+ * - Binary frames: Decode directly with codec
77
+ *
78
+ * Control messages (ping/pong/error) are always JSON text frames,
79
+ * regardless of what codec is used for data messages.
80
+ */
81
+ private handleRawMessage;
82
+ /**
83
+ * Check if a message is a ping message.
84
+ * Pings are always JSON with type: "ping".
85
+ */
86
+ private isPingMessage;
87
+ /**
88
+ * Send a pong response.
89
+ * Pongs are always JSON, bypassing the codec.
90
+ */
91
+ private sendPong;
92
+ }
93
+ //# sourceMappingURL=base-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-client.d.ts","sourceRoot":"","sources":["../src/base-client.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAEL,aAAa,EACb,KAAK,EAEL,cAAc,EACd,YAAY,EACZ,WAAW,EAEZ,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,YAAY,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IAChD,OAAO,CAAC,EAAE,CAA0B;IACpC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,SAAS,CAAU;IAC3B,OAAO,CAAC,UAAU,CAAmB;IAErC,gEAAgE;IACzD,SAAS,EAAE,cAAc,CAAC,CAAC,CAAC,CAAY;IAE/C,kEAAkE;IAC3D,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAY;IAEnD,wCAAwC;IACjC,OAAO,EAAE,WAAW,CAAY;IAEvC,2CAA2C;IACpC,OAAO,EAAE,YAAY,CAAY;gBAE5B,OAAO,GAAE,aAAa,CAAC,CAAC,EAAE,CAAC,CAAM;IAM7C,6DAA6D;IAC7D,IAAI,KAAK,IAAI,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAEvB;IAED;;;;OAIG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqCnC;;;OAGG;IACH,IAAI,CAAC,IAAI,EAAE,CAAC,GAAG,IAAI;IAQnB;;;;OAIG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAO5C;;OAEG;IACH,KAAK,IAAI,IAAI;IAOb;;OAEG;IACH,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;OAEG;IACH,IAAI,UAAU,IAAI,MAAM,CAEvB;IAED;;;;;;;OAOG;IACH,OAAO,CAAC,gBAAgB;IAgDxB;;;OAGG;IACH,OAAO,CAAC,aAAa;IASrB;;;OAGG;IACH,OAAO,CAAC,QAAQ;CAGjB"}
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ /**
3
+ * BaseWSClient - Low-level WebSocket client with automatic ping/pong handling.
4
+ *
5
+ * This client handles the connection lifecycle and heartbeat mechanism.
6
+ * It sends and receives raw JSON messages without any envelope wrapping.
7
+ *
8
+ * Use this directly for http/JSONConn servers, or as the base for GRPCWSClient.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.BaseWSClient = void 0;
12
+ const types_1 = require("./types");
13
+ /**
14
+ * Base WebSocket client with automatic ping/pong heartbeat handling.
15
+ *
16
+ * Features:
17
+ * - Automatic ping/pong response (keeps connection alive)
18
+ * - Promise-based connect()
19
+ * - Event handlers for messages, errors, and close
20
+ * - Connection state tracking
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const client = new BaseWSClient();
25
+ * client.onMessage = (data) => console.log('Received:', data);
26
+ * client.onClose = () => console.log('Disconnected');
27
+ * await client.connect('ws://localhost:8080/ws');
28
+ * client.send({ hello: 'world' });
29
+ * ```
30
+ */
31
+ class BaseWSClient {
32
+ constructor(options = {}) {
33
+ this.ws = null;
34
+ /** Called when a data message is received (decoded by codec) */
35
+ this.onMessage = () => { };
36
+ /** Called when a ping is received (after auto-pong if enabled) */
37
+ this.onPing = () => { };
38
+ /** Called when the connection closes */
39
+ this.onClose = () => { };
40
+ /** Called when a WebSocket error occurs */
41
+ this.onError = () => { };
42
+ this._autoPong = options.autoPong ?? true;
43
+ this._WebSocket = options.WebSocket ?? globalThis.WebSocket;
44
+ this._codec = options.codec ?? new types_1.JSONCodec();
45
+ }
46
+ /** Get the codec used for encoding/decoding data messages */
47
+ get codec() {
48
+ return this._codec;
49
+ }
50
+ /**
51
+ * Connect to a WebSocket server.
52
+ * @param url The WebSocket URL to connect to
53
+ * @returns Promise that resolves when connected
54
+ */
55
+ connect(url) {
56
+ return new Promise((resolve, reject) => {
57
+ if (this.ws && this.ws.readyState === types_1.ReadyState.OPEN) {
58
+ resolve();
59
+ return;
60
+ }
61
+ try {
62
+ this.ws = new this._WebSocket(url);
63
+ }
64
+ catch (error) {
65
+ reject(error);
66
+ return;
67
+ }
68
+ // Set binary type for proper ArrayBuffer handling
69
+ this.ws.binaryType = 'arraybuffer';
70
+ this.ws.onopen = () => {
71
+ resolve();
72
+ };
73
+ this.ws.onerror = (event) => {
74
+ const errorMsg = 'WebSocket error';
75
+ this.onError(errorMsg);
76
+ reject(new Error(errorMsg));
77
+ };
78
+ this.ws.onclose = () => {
79
+ this.onClose();
80
+ };
81
+ this.ws.onmessage = (event) => {
82
+ this.handleRawMessage(event.data);
83
+ };
84
+ });
85
+ }
86
+ /**
87
+ * Send a data message to the server using the configured codec.
88
+ * @param data The data to send (will be encoded by codec)
89
+ */
90
+ send(data) {
91
+ if (!this.ws || this.ws.readyState !== types_1.ReadyState.OPEN) {
92
+ throw new Error('WebSocket is not connected');
93
+ }
94
+ const encoded = this._codec.encode(data);
95
+ this.ws.send(encoded);
96
+ }
97
+ /**
98
+ * Send a raw message to the server (bypasses codec).
99
+ * Useful for control messages like pong.
100
+ * @param message The raw string or ArrayBuffer to send
101
+ */
102
+ sendRaw(message) {
103
+ if (!this.ws || this.ws.readyState !== types_1.ReadyState.OPEN) {
104
+ throw new Error('WebSocket is not connected');
105
+ }
106
+ this.ws.send(message);
107
+ }
108
+ /**
109
+ * Close the WebSocket connection.
110
+ */
111
+ close() {
112
+ if (this.ws) {
113
+ this.ws.close();
114
+ this.ws = null;
115
+ }
116
+ }
117
+ /**
118
+ * Check if the client is connected.
119
+ */
120
+ get isConnected() {
121
+ return this.ws !== null && this.ws.readyState === types_1.ReadyState.OPEN;
122
+ }
123
+ /**
124
+ * Get the WebSocket ready state.
125
+ */
126
+ get readyState() {
127
+ return this.ws?.readyState ?? types_1.ReadyState.CLOSED;
128
+ }
129
+ /**
130
+ * Handle incoming raw message data.
131
+ * - Text frames: Check for control messages (ping), then decode with codec
132
+ * - Binary frames: Decode directly with codec
133
+ *
134
+ * Control messages (ping/pong/error) are always JSON text frames,
135
+ * regardless of what codec is used for data messages.
136
+ */
137
+ handleRawMessage(data) {
138
+ // Binary frame -> decode with codec directly
139
+ if (data instanceof ArrayBuffer) {
140
+ try {
141
+ const decoded = this._codec.decode(data);
142
+ this.onMessage(decoded);
143
+ }
144
+ catch (err) {
145
+ this.onError(`Failed to decode binary message: ${err}`);
146
+ }
147
+ return;
148
+ }
149
+ // Text frame -> check for control messages first
150
+ let parsed;
151
+ try {
152
+ parsed = JSON.parse(data);
153
+ }
154
+ catch {
155
+ // Not valid JSON, try to decode with codec
156
+ try {
157
+ const decoded = this._codec.decode(data);
158
+ this.onMessage(decoded);
159
+ }
160
+ catch (err) {
161
+ this.onError(`Failed to decode text message: ${err}`);
162
+ }
163
+ return;
164
+ }
165
+ // Check if it's a ping message (control message)
166
+ if (this.isPingMessage(parsed)) {
167
+ const pingId = parsed.pingId;
168
+ if (this._autoPong && pingId !== undefined) {
169
+ this.sendPong(pingId);
170
+ }
171
+ this.onPing(pingId ?? 0);
172
+ return;
173
+ }
174
+ // Not a control message -> decode with codec
175
+ // For JSON codec, the parsed object is already decoded
176
+ // For other codecs, we pass the raw string
177
+ try {
178
+ const decoded = this._codec.decode(data);
179
+ this.onMessage(decoded);
180
+ }
181
+ catch (err) {
182
+ this.onError(`Failed to decode message: ${err}`);
183
+ }
184
+ }
185
+ /**
186
+ * Check if a message is a ping message.
187
+ * Pings are always JSON with type: "ping".
188
+ */
189
+ isPingMessage(msg) {
190
+ return (typeof msg === 'object' &&
191
+ msg !== null &&
192
+ 'type' in msg &&
193
+ msg.type === 'ping');
194
+ }
195
+ /**
196
+ * Send a pong response.
197
+ * Pongs are always JSON, bypassing the codec.
198
+ */
199
+ sendPong(pingId) {
200
+ this.sendRaw(JSON.stringify({ type: 'pong', pingId }));
201
+ }
202
+ }
203
+ exports.BaseWSClient = BaseWSClient;
204
+ //# sourceMappingURL=base-client.js.map