@pokertools/sdk 1.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.
@@ -0,0 +1,1090 @@
1
+ import { createContext, useState, useRef, useEffect, useCallback, useMemo, useContext } from 'react';
2
+ import { safeParseServerMessage } from '@pokertools/types';
3
+ import { jsx } from 'react/jsx-runtime';
4
+
5
+ // src/react/index.tsx
6
+
7
+ // src/types.ts
8
+ var PokerSDKError = class extends Error {
9
+ constructor(message, code, statusCode, details) {
10
+ super(message);
11
+ this.code = code;
12
+ this.statusCode = statusCode;
13
+ this.details = details;
14
+ this.name = "PokerSDKError";
15
+ }
16
+ };
17
+
18
+ // src/client.ts
19
+ var DEFAULT_CONFIG = {
20
+ timeout: 3e4,
21
+ retry: {
22
+ count: 3,
23
+ delay: 1e3,
24
+ backoff: 2
25
+ }
26
+ };
27
+ var PokerClient = class {
28
+ constructor(config) {
29
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
30
+ this.timeout = config.timeout ?? DEFAULT_CONFIG.timeout;
31
+ this.retry = {
32
+ count: config.retry?.count ?? DEFAULT_CONFIG.retry.count,
33
+ delay: config.retry?.delay ?? DEFAULT_CONFIG.retry.delay,
34
+ backoff: config.retry?.backoff ?? DEFAULT_CONFIG.retry.backoff
35
+ };
36
+ this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
37
+ this.debug = config.debug ?? false;
38
+ this.token = config.token ?? null;
39
+ }
40
+ // ============================================================================
41
+ // Configuration
42
+ // ============================================================================
43
+ /**
44
+ * Set the authentication token
45
+ */
46
+ setToken(token) {
47
+ this.token = token;
48
+ }
49
+ /**
50
+ * Get current token
51
+ */
52
+ getToken() {
53
+ return this.token;
54
+ }
55
+ /**
56
+ * Check if client is authenticated
57
+ */
58
+ isAuthenticated() {
59
+ return this.token !== null;
60
+ }
61
+ // ============================================================================
62
+ // Authentication
63
+ // ============================================================================
64
+ /**
65
+ * Get a nonce for SIWE authentication
66
+ */
67
+ async getNonce() {
68
+ const response = await this.request("POST", "/auth/nonce");
69
+ return response.nonce;
70
+ }
71
+ /**
72
+ * Login with SIWE signature
73
+ */
74
+ async login(request) {
75
+ const response = await this.request("POST", "/auth/login", request);
76
+ this.token = response.token;
77
+ return response;
78
+ }
79
+ /**
80
+ * Logout and revoke session
81
+ */
82
+ async logout() {
83
+ await this.request("POST", "/auth/logout");
84
+ this.token = null;
85
+ }
86
+ // ============================================================================
87
+ // Tables
88
+ // ============================================================================
89
+ /**
90
+ * Get list of active tables
91
+ */
92
+ async getTables() {
93
+ const response = await this.request("GET", "/tables");
94
+ return response.tables;
95
+ }
96
+ /**
97
+ * Create a new table
98
+ */
99
+ async createTable(config) {
100
+ const response = await this.request("POST", "/tables", config);
101
+ return response.tableId;
102
+ }
103
+ /**
104
+ * Get table state
105
+ * @param tableId - Table ID
106
+ * @param since - Optional version for conditional fetch (returns null if unchanged)
107
+ */
108
+ async getTableState(tableId, since) {
109
+ const query = since !== void 0 ? `?since=${since}` : "";
110
+ try {
111
+ const response = await this.request(
112
+ "GET",
113
+ `/tables/${tableId}${query}`
114
+ );
115
+ return response.state;
116
+ } catch (error) {
117
+ if (error instanceof PokerSDKError && error.statusCode === 304) {
118
+ return null;
119
+ }
120
+ throw error;
121
+ }
122
+ }
123
+ /**
124
+ * Buy in to a table
125
+ */
126
+ async buyIn(tableId, request) {
127
+ await this.request("POST", `/tables/${tableId}/buy-in`, request);
128
+ }
129
+ /**
130
+ * Execute a game action
131
+ */
132
+ async action(tableId, request) {
133
+ const response = await this.request(
134
+ "POST",
135
+ `/tables/${tableId}/action`,
136
+ request
137
+ );
138
+ return response.state;
139
+ }
140
+ /**
141
+ * Add chips to stack (rebuy/top-up)
142
+ */
143
+ async addChips(tableId, request) {
144
+ await this.request("POST", `/tables/${tableId}/add-chips`, request);
145
+ }
146
+ /**
147
+ * Stand from table (leave and cash out)
148
+ */
149
+ async stand(tableId) {
150
+ await this.request("POST", `/tables/${tableId}/stand`);
151
+ }
152
+ // ============================================================================
153
+ // Convenience Action Methods
154
+ // ============================================================================
155
+ /**
156
+ * Fold hand
157
+ */
158
+ async fold(tableId) {
159
+ return this.action(tableId, { type: "FOLD" });
160
+ }
161
+ /**
162
+ * Check (pass action)
163
+ */
164
+ async check(tableId) {
165
+ return this.action(tableId, { type: "CHECK" });
166
+ }
167
+ /**
168
+ * Call current bet
169
+ */
170
+ async call(tableId) {
171
+ return this.action(tableId, { type: "CALL" });
172
+ }
173
+ /**
174
+ * Place a bet
175
+ */
176
+ async bet(tableId, amount) {
177
+ return this.action(tableId, { type: "BET", amount });
178
+ }
179
+ /**
180
+ * Raise the current bet
181
+ */
182
+ async raise(tableId, amount) {
183
+ return this.action(tableId, { type: "RAISE", amount });
184
+ }
185
+ /**
186
+ * Deal new hand
187
+ */
188
+ async deal(tableId) {
189
+ return this.action(tableId, { type: "DEAL" });
190
+ }
191
+ /**
192
+ * Show cards at showdown
193
+ */
194
+ async show(tableId, cardIndices) {
195
+ return this.action(tableId, { type: "SHOW", cardIndices });
196
+ }
197
+ /**
198
+ * Muck cards at showdown
199
+ */
200
+ async muck(tableId) {
201
+ return this.action(tableId, { type: "MUCK" });
202
+ }
203
+ /**
204
+ * Use time bank
205
+ */
206
+ async timeBank(tableId) {
207
+ return this.action(tableId, { type: "TIME_BANK" });
208
+ }
209
+ // ============================================================================
210
+ // User
211
+ // ============================================================================
212
+ /**
213
+ * Get current user profile and balances
214
+ */
215
+ async getProfile() {
216
+ return this.request("GET", "/user/me");
217
+ }
218
+ /**
219
+ * Get hand history
220
+ */
221
+ async getHandHistory() {
222
+ const response = await this.request("GET", "/user/history");
223
+ return response.history;
224
+ }
225
+ /**
226
+ * Request a withdrawal
227
+ */
228
+ async withdraw(request) {
229
+ return this.request("POST", "/user/withdraw", request);
230
+ }
231
+ /**
232
+ * Get withdrawal history
233
+ */
234
+ async getWithdrawals() {
235
+ const response = await this.request(
236
+ "GET",
237
+ "/user/withdrawals"
238
+ );
239
+ return response.withdrawals;
240
+ }
241
+ // ============================================================================
242
+ // Finance
243
+ // ============================================================================
244
+ /**
245
+ * Get supported blockchains and tokens
246
+ */
247
+ async getChains() {
248
+ return this.request("GET", "/finance/chains");
249
+ }
250
+ /**
251
+ * Start deposit monitoring session
252
+ */
253
+ async startDeposit() {
254
+ return this.request("POST", "/finance/deposit/start");
255
+ }
256
+ /**
257
+ * Get deposit address
258
+ */
259
+ async getDepositAddress() {
260
+ const response = await this.request("GET", "/finance/deposit/address");
261
+ return response.address;
262
+ }
263
+ /**
264
+ * Get deposit history
265
+ */
266
+ async getDeposits() {
267
+ const response = await this.request("GET", "/finance/deposits");
268
+ return response.deposits;
269
+ }
270
+ // ============================================================================
271
+ // Notes
272
+ // ============================================================================
273
+ /**
274
+ * Get all notes by current user
275
+ */
276
+ async getNotes() {
277
+ const response = await this.request("GET", "/notes");
278
+ return response.notes;
279
+ }
280
+ /**
281
+ * Get note for specific player
282
+ */
283
+ async getNote(targetId) {
284
+ const response = await this.request("GET", `/notes/${targetId}`);
285
+ return response.note;
286
+ }
287
+ /**
288
+ * Save or update note
289
+ */
290
+ async saveNote(targetId, content, label) {
291
+ const response = await this.request("POST", "/notes", {
292
+ targetId,
293
+ content,
294
+ label
295
+ });
296
+ return response.note;
297
+ }
298
+ /**
299
+ * Delete note
300
+ */
301
+ async deleteNote(targetId) {
302
+ await this.request("DELETE", `/notes/${targetId}`);
303
+ }
304
+ // ============================================================================
305
+ // Health
306
+ // ============================================================================
307
+ /**
308
+ * Health check
309
+ */
310
+ async health() {
311
+ return this.request("GET", "/health");
312
+ }
313
+ // ============================================================================
314
+ // Private Methods
315
+ // ============================================================================
316
+ /**
317
+ * Make HTTP request with retry logic
318
+ */
319
+ async request(method, path, body) {
320
+ const url = `${this.baseUrl}${path}`;
321
+ const headers = {
322
+ "Content-Type": "application/json"
323
+ };
324
+ if (this.token) {
325
+ headers.Authorization = `Bearer ${this.token}`;
326
+ }
327
+ let lastError = null;
328
+ for (let attempt = 0; attempt <= this.retry.count; attempt++) {
329
+ try {
330
+ const controller = new AbortController();
331
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
332
+ if (this.debug) {
333
+ console.log(`[PokerSDK] ${method} ${path}`, body);
334
+ }
335
+ const response = await this.fetchFn(url, {
336
+ method,
337
+ headers,
338
+ body: body ? JSON.stringify(body) : void 0,
339
+ signal: controller.signal
340
+ });
341
+ clearTimeout(timeoutId);
342
+ if (response.status === 304) {
343
+ throw new PokerSDKError("Not Modified", "NOT_MODIFIED", 304);
344
+ }
345
+ if (!response.ok) {
346
+ const errorData = await response.json().catch(() => ({}));
347
+ throw new PokerSDKError(
348
+ errorData.message ?? errorData.error ?? `HTTP ${response.status}`,
349
+ errorData.code ?? errorData.error ?? "HTTP_ERROR",
350
+ response.status,
351
+ errorData
352
+ );
353
+ }
354
+ const data = await response.json();
355
+ if (this.debug) {
356
+ console.log(`[PokerSDK] Response:`, data);
357
+ }
358
+ return data;
359
+ } catch (error) {
360
+ lastError = error;
361
+ if (error instanceof PokerSDKError) {
362
+ if (error.statusCode && error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
363
+ throw error;
364
+ }
365
+ }
366
+ if (error instanceof Error && error.name === "AbortError") {
367
+ throw new PokerSDKError("Request timeout", "TIMEOUT", void 0, {
368
+ timeout: this.timeout
369
+ });
370
+ }
371
+ if (attempt < this.retry.count) {
372
+ const delay = this.retry.delay * Math.pow(this.retry.backoff, attempt);
373
+ if (this.debug) {
374
+ console.log(`[PokerSDK] Retry ${attempt + 1}/${this.retry.count} in ${delay}ms`);
375
+ }
376
+ await this.sleep(delay);
377
+ }
378
+ }
379
+ }
380
+ throw lastError ?? new PokerSDKError("Request failed", "REQUEST_FAILED");
381
+ }
382
+ /**
383
+ * Sleep helper
384
+ */
385
+ sleep(ms) {
386
+ return new Promise((resolve) => setTimeout(resolve, ms));
387
+ }
388
+ };
389
+ var DEFAULT_SOCKET_CONFIG = {
390
+ heartbeatInterval: 25e3,
391
+ reconnectAttempts: 10,
392
+ reconnectDelay: 1e3,
393
+ maxReconnectDelay: 3e4
394
+ };
395
+ var PokerSocket = class _PokerSocket {
396
+ constructor(config) {
397
+ this.ws = null;
398
+ this.connectionState = "disconnected";
399
+ this.reconnectCount = 0;
400
+ this.heartbeatTimer = null;
401
+ this.pendingRequests = /* @__PURE__ */ new Map();
402
+ this.joinedTables = /* @__PURE__ */ new Set();
403
+ this.listeners = /* @__PURE__ */ new Map();
404
+ this.shouldReconnect = true;
405
+ // Latest state cache for each table
406
+ this.stateCache = /* @__PURE__ */ new Map();
407
+ const wsUrl = new URL(config.url);
408
+ wsUrl.searchParams.set("token", config.token);
409
+ this.url = wsUrl.toString();
410
+ this.token = config.token;
411
+ this.heartbeatInterval = config.heartbeatInterval ?? DEFAULT_SOCKET_CONFIG.heartbeatInterval;
412
+ this.reconnectAttempts = config.reconnectAttempts ?? DEFAULT_SOCKET_CONFIG.reconnectAttempts;
413
+ this.reconnectDelay = config.reconnectDelay ?? DEFAULT_SOCKET_CONFIG.reconnectDelay;
414
+ this.maxReconnectDelay = config.maxReconnectDelay ?? DEFAULT_SOCKET_CONFIG.maxReconnectDelay;
415
+ this.WebSocketImpl = config.WebSocket ?? globalThis.WebSocket;
416
+ this.debug = config.debug ?? false;
417
+ }
418
+ /**
419
+ * Create a PokerSocket from SDK config
420
+ */
421
+ static fromConfig(config) {
422
+ if (!config.token) {
423
+ throw new PokerSDKError("Token is required for WebSocket connection", "AUTH_REQUIRED");
424
+ }
425
+ const baseUrl = config.baseUrl.replace(/\/$/, "");
426
+ const wsUrl = config.wsUrl ?? baseUrl.replace(/^http/, "ws") + "/ws/play";
427
+ return new _PokerSocket({
428
+ url: wsUrl,
429
+ token: config.token,
430
+ WebSocket: config.WebSocket,
431
+ debug: config.debug
432
+ });
433
+ }
434
+ // ============================================================================
435
+ // Connection Management
436
+ // ============================================================================
437
+ /**
438
+ * Connect to the WebSocket server
439
+ */
440
+ connect() {
441
+ return new Promise((resolve, reject) => {
442
+ if (this.connectionState === "connected") {
443
+ resolve();
444
+ return;
445
+ }
446
+ if (this.connectionState === "connecting") {
447
+ const checkConnection = () => {
448
+ if (this.connectionState === "connected") {
449
+ resolve();
450
+ } else if (this.connectionState === "disconnected") {
451
+ reject(new PokerSDKError("Connection failed", "CONNECTION_FAILED"));
452
+ } else {
453
+ setTimeout(checkConnection, 100);
454
+ }
455
+ };
456
+ checkConnection();
457
+ return;
458
+ }
459
+ this.shouldReconnect = true;
460
+ this.connectionState = "connecting";
461
+ this.log("Connecting to", this.url);
462
+ try {
463
+ this.ws = new this.WebSocketImpl(this.url);
464
+ this.ws.onopen = () => {
465
+ this.connectionState = "connected";
466
+ this.reconnectCount = 0;
467
+ this.startHeartbeat();
468
+ this.emit("connect");
469
+ this.log("Connected");
470
+ void this.rejoinTables();
471
+ resolve();
472
+ };
473
+ this.ws.onclose = (event) => {
474
+ this.handleDisconnect(event.reason || "Connection closed");
475
+ };
476
+ this.ws.onerror = (event) => {
477
+ this.log("WebSocket error:", event);
478
+ if (this.connectionState === "connecting") {
479
+ reject(new PokerSDKError("Connection failed", "CONNECTION_FAILED"));
480
+ }
481
+ };
482
+ this.ws.onmessage = (event) => {
483
+ this.handleMessage(event.data);
484
+ };
485
+ } catch (error) {
486
+ this.connectionState = "disconnected";
487
+ reject(error);
488
+ }
489
+ });
490
+ }
491
+ /**
492
+ * Disconnect from the WebSocket server
493
+ */
494
+ disconnect() {
495
+ this.shouldReconnect = false;
496
+ this.stopHeartbeat();
497
+ this.clearPendingRequests("Connection closed");
498
+ if (this.ws) {
499
+ this.ws.close(1e3, "Client disconnect");
500
+ this.ws = null;
501
+ }
502
+ this.connectionState = "disconnected";
503
+ this.emit("disconnect", "Client disconnect");
504
+ this.log("Disconnected");
505
+ }
506
+ /**
507
+ * Get current connection state
508
+ */
509
+ getState() {
510
+ return this.connectionState;
511
+ }
512
+ /**
513
+ * Check if connected
514
+ */
515
+ isConnected() {
516
+ return this.connectionState === "connected";
517
+ }
518
+ // ============================================================================
519
+ // Table Subscription
520
+ // ============================================================================
521
+ /**
522
+ * Join a table to receive real-time updates
523
+ */
524
+ async join(tableId) {
525
+ if (this.connectionState !== "connected") {
526
+ throw new PokerSDKError("Not connected", "NOT_CONNECTED");
527
+ }
528
+ const requestId = this.generateRequestId();
529
+ const message = {
530
+ type: "JOIN",
531
+ tableId,
532
+ requestId
533
+ };
534
+ this.joinedTables.add(tableId);
535
+ this.send(message);
536
+ return new Promise((resolve, reject) => {
537
+ const timeout = setTimeout(() => {
538
+ this.pendingRequests.delete(requestId);
539
+ reject(new PokerSDKError("Join timeout", "TIMEOUT"));
540
+ }, 1e4);
541
+ this.pendingRequests.set(`snapshot:${tableId}`, {
542
+ resolve: (state) => {
543
+ clearTimeout(timeout);
544
+ resolve(state);
545
+ },
546
+ reject,
547
+ timeout
548
+ });
549
+ });
550
+ }
551
+ /**
552
+ * Leave a table
553
+ */
554
+ leave(tableId) {
555
+ if (this.connectionState !== "connected") {
556
+ return;
557
+ }
558
+ this.joinedTables.delete(tableId);
559
+ this.stateCache.delete(tableId);
560
+ const message = {
561
+ type: "LEAVE",
562
+ tableId
563
+ };
564
+ this.send(message);
565
+ }
566
+ /**
567
+ * Get currently joined tables
568
+ */
569
+ getJoinedTables() {
570
+ return Array.from(this.joinedTables);
571
+ }
572
+ /**
573
+ * Get cached state for a table
574
+ */
575
+ getCachedState(tableId) {
576
+ return this.stateCache.get(tableId);
577
+ }
578
+ // ============================================================================
579
+ // Event Handling
580
+ // ============================================================================
581
+ /**
582
+ * Subscribe to an event
583
+ */
584
+ on(event, listener) {
585
+ if (!this.listeners.has(event)) {
586
+ this.listeners.set(event, /* @__PURE__ */ new Set());
587
+ }
588
+ this.listeners.get(event).add(listener);
589
+ return () => {
590
+ this.off(event, listener);
591
+ };
592
+ }
593
+ /**
594
+ * Unsubscribe from an event
595
+ */
596
+ off(event, listener) {
597
+ const listeners = this.listeners.get(event);
598
+ if (listeners) {
599
+ listeners.delete(listener);
600
+ }
601
+ }
602
+ /**
603
+ * Subscribe to an event (once)
604
+ */
605
+ once(event, listener) {
606
+ const onceWrapper = ((...args) => {
607
+ this.off(event, onceWrapper);
608
+ listener(...args);
609
+ });
610
+ return this.on(event, onceWrapper);
611
+ }
612
+ // ============================================================================
613
+ // Ping
614
+ // ============================================================================
615
+ /**
616
+ * Send application-level ping (not WebSocket ping)
617
+ */
618
+ async ping() {
619
+ if (this.connectionState !== "connected") {
620
+ throw new PokerSDKError("Not connected", "NOT_CONNECTED");
621
+ }
622
+ const requestId = this.generateRequestId();
623
+ const startTime = Date.now();
624
+ const message = {
625
+ type: "PING",
626
+ requestId,
627
+ timestamp: startTime
628
+ };
629
+ this.send(message);
630
+ return new Promise((resolve, reject) => {
631
+ const timeout = setTimeout(() => {
632
+ this.pendingRequests.delete(requestId);
633
+ reject(new PokerSDKError("Ping timeout", "TIMEOUT"));
634
+ }, 5e3);
635
+ this.pendingRequests.set(requestId, {
636
+ resolve: () => {
637
+ resolve(Date.now() - startTime);
638
+ },
639
+ reject,
640
+ timeout
641
+ });
642
+ });
643
+ }
644
+ // ============================================================================
645
+ // Private Methods
646
+ // ============================================================================
647
+ /**
648
+ * Send a message to the server
649
+ */
650
+ send(message) {
651
+ if (this.ws?.readyState !== this.WebSocketImpl.OPEN) {
652
+ throw new PokerSDKError("WebSocket not open", "NOT_CONNECTED");
653
+ }
654
+ this.log("Sending:", message);
655
+ this.ws.send(JSON.stringify(message));
656
+ }
657
+ /**
658
+ * Handle incoming message
659
+ */
660
+ handleMessage(data) {
661
+ try {
662
+ const parsed = JSON.parse(data);
663
+ const result = safeParseServerMessage(parsed);
664
+ if (!result.success) {
665
+ this.log("Invalid server message:", result.error);
666
+ return;
667
+ }
668
+ const message = result.data;
669
+ this.log("Received:", message);
670
+ switch (message.type) {
671
+ case "SNAPSHOT": {
672
+ this.stateCache.set(message.tableId, message.state);
673
+ const pending = this.pendingRequests.get(`snapshot:${message.tableId}`);
674
+ if (pending) {
675
+ this.pendingRequests.delete(`snapshot:${message.tableId}`);
676
+ pending.resolve(message.state);
677
+ }
678
+ this.emit("snapshot", message.tableId, message.state);
679
+ break;
680
+ }
681
+ case "STATE_UPDATE": {
682
+ const cachedState = this.stateCache.get(message.tableId);
683
+ if (cachedState) {
684
+ const updatedState = { ...cachedState, version: message.version };
685
+ this.stateCache.set(message.tableId, updatedState);
686
+ this.emit("stateUpdate", message.tableId, updatedState);
687
+ } else {
688
+ this.emit("stateUpdate", message.tableId, {
689
+ version: message.version
690
+ });
691
+ }
692
+ break;
693
+ }
694
+ case "ACTION": {
695
+ this.emit(
696
+ "action",
697
+ message.tableId,
698
+ message.playerId,
699
+ message.actionType,
700
+ message.amount
701
+ );
702
+ break;
703
+ }
704
+ case "ACK": {
705
+ const pending = this.pendingRequests.get(message.requestId);
706
+ if (pending) {
707
+ clearTimeout(pending.timeout);
708
+ this.pendingRequests.delete(message.requestId);
709
+ pending.resolve(void 0);
710
+ }
711
+ break;
712
+ }
713
+ case "PONG": {
714
+ const pending = this.pendingRequests.get(message.requestId);
715
+ if (pending) {
716
+ clearTimeout(pending.timeout);
717
+ this.pendingRequests.delete(message.requestId);
718
+ pending.resolve(message.timestamp);
719
+ }
720
+ break;
721
+ }
722
+ case "ERROR": {
723
+ this.log("Server error:", message);
724
+ if (message.requestId) {
725
+ const pending = this.pendingRequests.get(message.requestId);
726
+ if (pending) {
727
+ clearTimeout(pending.timeout);
728
+ this.pendingRequests.delete(message.requestId);
729
+ pending.reject(new PokerSDKError(message.message, message.code));
730
+ }
731
+ }
732
+ this.emit("error", new PokerSDKError(message.message, message.code));
733
+ break;
734
+ }
735
+ }
736
+ } catch (error) {
737
+ this.log("Failed to parse message:", error);
738
+ }
739
+ }
740
+ /**
741
+ * Handle disconnect
742
+ */
743
+ handleDisconnect(reason) {
744
+ this.stopHeartbeat();
745
+ this.ws = null;
746
+ const wasConnected = this.connectionState === "connected";
747
+ this.connectionState = "disconnected";
748
+ if (wasConnected) {
749
+ this.emit("disconnect", reason);
750
+ }
751
+ if (this.shouldReconnect && this.reconnectCount < this.reconnectAttempts) {
752
+ void this.reconnect();
753
+ }
754
+ }
755
+ /**
756
+ * Attempt to reconnect
757
+ */
758
+ async reconnect() {
759
+ this.reconnectCount++;
760
+ this.connectionState = "reconnecting";
761
+ const delay = Math.min(
762
+ this.reconnectDelay * Math.pow(2, this.reconnectCount - 1),
763
+ this.maxReconnectDelay
764
+ );
765
+ this.log(
766
+ `Reconnecting in ${delay}ms (attempt ${this.reconnectCount}/${this.reconnectAttempts})`
767
+ );
768
+ this.emit("reconnect", this.reconnectCount);
769
+ await this.sleep(delay);
770
+ if (!this.shouldReconnect) {
771
+ return;
772
+ }
773
+ try {
774
+ await this.connect();
775
+ } catch {
776
+ }
777
+ }
778
+ /**
779
+ * Rejoin previously joined tables
780
+ */
781
+ async rejoinTables() {
782
+ for (const tableId of this.joinedTables) {
783
+ try {
784
+ await this.join(tableId);
785
+ } catch (error) {
786
+ this.log("Failed to rejoin table:", tableId, error);
787
+ }
788
+ }
789
+ }
790
+ /**
791
+ * Start heartbeat timer
792
+ */
793
+ startHeartbeat() {
794
+ this.stopHeartbeat();
795
+ this.heartbeatTimer = setInterval(() => {
796
+ if (this.connectionState === "connected") {
797
+ void this.ping().catch(() => {
798
+ this.log("Heartbeat failed");
799
+ });
800
+ }
801
+ }, this.heartbeatInterval);
802
+ }
803
+ /**
804
+ * Stop heartbeat timer
805
+ */
806
+ stopHeartbeat() {
807
+ if (this.heartbeatTimer) {
808
+ clearInterval(this.heartbeatTimer);
809
+ this.heartbeatTimer = null;
810
+ }
811
+ }
812
+ /**
813
+ * Clear all pending requests
814
+ */
815
+ clearPendingRequests(reason) {
816
+ for (const pending of this.pendingRequests.values()) {
817
+ clearTimeout(pending.timeout);
818
+ pending.reject(new PokerSDKError(reason, "CONNECTION_CLOSED"));
819
+ }
820
+ this.pendingRequests.clear();
821
+ }
822
+ /**
823
+ * Emit event to listeners
824
+ */
825
+ emit(event, ...args) {
826
+ const listeners = this.listeners.get(event);
827
+ if (listeners) {
828
+ for (const listener of listeners) {
829
+ try {
830
+ listener(...args);
831
+ } catch (error) {
832
+ this.log("Listener error:", error);
833
+ }
834
+ }
835
+ }
836
+ }
837
+ /**
838
+ * Generate unique request ID
839
+ */
840
+ generateRequestId() {
841
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
842
+ }
843
+ /**
844
+ * Sleep helper
845
+ */
846
+ sleep(ms) {
847
+ return new Promise((resolve) => setTimeout(resolve, ms));
848
+ }
849
+ /**
850
+ * Debug logger
851
+ */
852
+ log(...args) {
853
+ if (this.debug) {
854
+ console.log("[PokerSocket]", ...args);
855
+ }
856
+ }
857
+ };
858
+ var PokerContext = createContext(null);
859
+ function PokerProvider({ config, children, autoConnect = true }) {
860
+ const [connectionState, setConnectionState] = useState("disconnected");
861
+ const clientRef = useRef(null);
862
+ const socketRef = useRef(null);
863
+ clientRef.current ?? (clientRef.current = new PokerClient(config));
864
+ useEffect(() => {
865
+ if (clientRef.current) {
866
+ clientRef.current.setToken(config.token ?? null);
867
+ }
868
+ }, [config.token]);
869
+ useEffect(() => {
870
+ if (config.token && autoConnect && !socketRef.current) {
871
+ socketRef.current = PokerSocket.fromConfig(config);
872
+ socketRef.current.on("connect", () => setConnectionState("connected"));
873
+ socketRef.current.on("disconnect", () => setConnectionState("disconnected"));
874
+ socketRef.current.on("reconnect", () => setConnectionState("reconnecting"));
875
+ void socketRef.current.connect().catch(console.error);
876
+ }
877
+ return () => {
878
+ if (socketRef.current) {
879
+ socketRef.current.disconnect();
880
+ socketRef.current = null;
881
+ }
882
+ };
883
+ }, [config.token, autoConnect, config]);
884
+ const connect = useCallback(async () => {
885
+ if (!config.token) {
886
+ throw new Error("Token required to connect");
887
+ }
888
+ if (!socketRef.current) {
889
+ socketRef.current = PokerSocket.fromConfig(config);
890
+ socketRef.current.on("connect", () => setConnectionState("connected"));
891
+ socketRef.current.on("disconnect", () => setConnectionState("disconnected"));
892
+ socketRef.current.on("reconnect", () => setConnectionState("reconnecting"));
893
+ }
894
+ setConnectionState("connecting");
895
+ await socketRef.current.connect();
896
+ }, [config]);
897
+ const disconnect = useCallback(() => {
898
+ if (socketRef.current) {
899
+ socketRef.current.disconnect();
900
+ }
901
+ }, []);
902
+ const value = useMemo(
903
+ () => ({
904
+ client: clientRef.current,
905
+ socket: socketRef.current,
906
+ isAuthenticated: !!config.token,
907
+ connectionState,
908
+ connect,
909
+ disconnect
910
+ }),
911
+ [config.token, connectionState, connect, disconnect]
912
+ );
913
+ return /* @__PURE__ */ jsx(PokerContext.Provider, { value, children });
914
+ }
915
+ function usePoker() {
916
+ const context = useContext(PokerContext);
917
+ if (!context) {
918
+ throw new Error("usePoker must be used within a PokerProvider");
919
+ }
920
+ return context;
921
+ }
922
+ function usePokerClient() {
923
+ return usePoker().client;
924
+ }
925
+ function usePokerSocket() {
926
+ return usePoker().socket;
927
+ }
928
+ function useTable(tableId, options = {}) {
929
+ const { pollInterval, autoJoin = true } = options;
930
+ const { client, socket } = usePoker();
931
+ const [state, setState] = useState(null);
932
+ const [isLoading, setIsLoading] = useState(true);
933
+ const [error, setError] = useState(null);
934
+ const versionRef = useRef(0);
935
+ const refresh = useCallback(async () => {
936
+ try {
937
+ setIsLoading(true);
938
+ const newState = await client.getTableState(tableId);
939
+ if (newState) {
940
+ setState(newState);
941
+ versionRef.current = newState.version;
942
+ }
943
+ setError(null);
944
+ } catch (err) {
945
+ setError(err);
946
+ } finally {
947
+ setIsLoading(false);
948
+ }
949
+ }, [client, tableId]);
950
+ useEffect(() => {
951
+ void refresh();
952
+ }, [refresh]);
953
+ useEffect(() => {
954
+ if (!socket || !autoJoin) return;
955
+ const handleStateUpdate = (id, newState) => {
956
+ if (id === tableId) {
957
+ setState(newState);
958
+ versionRef.current = newState.version;
959
+ }
960
+ };
961
+ const handleSnapshot = (id, newState) => {
962
+ if (id === tableId) {
963
+ setState(newState);
964
+ versionRef.current = newState.version;
965
+ setIsLoading(false);
966
+ }
967
+ };
968
+ socket.on("stateUpdate", handleStateUpdate);
969
+ socket.on("snapshot", handleSnapshot);
970
+ if (socket.isConnected()) {
971
+ void socket.join(tableId).catch(console.error);
972
+ }
973
+ return () => {
974
+ socket.off("stateUpdate", handleStateUpdate);
975
+ socket.off("snapshot", handleSnapshot);
976
+ socket.leave(tableId);
977
+ };
978
+ }, [socket, tableId, autoJoin]);
979
+ useEffect(() => {
980
+ if (!pollInterval) return;
981
+ const interval = setInterval(() => {
982
+ void (async () => {
983
+ const newState = await client.getTableState(tableId, versionRef.current);
984
+ if (newState) {
985
+ setState(newState);
986
+ versionRef.current = newState.version;
987
+ }
988
+ })();
989
+ }, pollInterval);
990
+ return () => clearInterval(interval);
991
+ }, [client, tableId, pollInterval]);
992
+ const action = useCallback(
993
+ async (type, amount) => {
994
+ const newState = await client.action(tableId, { type, amount });
995
+ setState(newState);
996
+ versionRef.current = newState.version;
997
+ },
998
+ [client, tableId]
999
+ );
1000
+ const leave = useCallback(async () => {
1001
+ await client.stand(tableId);
1002
+ if (socket) {
1003
+ socket.leave(tableId);
1004
+ }
1005
+ }, [client, socket, tableId]);
1006
+ return { state, isLoading, error, refresh, action, leave };
1007
+ }
1008
+ function useUser() {
1009
+ const { client, isAuthenticated } = usePoker();
1010
+ const [profile, setProfile] = useState(null);
1011
+ const [isLoading, setIsLoading] = useState(false);
1012
+ const [error, setError] = useState(null);
1013
+ const refresh = useCallback(async () => {
1014
+ if (!isAuthenticated) return;
1015
+ try {
1016
+ setIsLoading(true);
1017
+ const data = await client.getProfile();
1018
+ setProfile(data);
1019
+ setError(null);
1020
+ } catch (err) {
1021
+ setError(err);
1022
+ } finally {
1023
+ setIsLoading(false);
1024
+ }
1025
+ }, [client, isAuthenticated]);
1026
+ useEffect(() => {
1027
+ if (isAuthenticated) {
1028
+ void refresh();
1029
+ } else {
1030
+ setProfile(null);
1031
+ }
1032
+ }, [isAuthenticated, refresh]);
1033
+ return {
1034
+ profile,
1035
+ balances: profile?.balances ?? null,
1036
+ isLoading,
1037
+ error,
1038
+ refresh
1039
+ };
1040
+ }
1041
+ function useTables() {
1042
+ const { client } = usePoker();
1043
+ const [tables, setTables] = useState([]);
1044
+ const [isLoading, setIsLoading] = useState(true);
1045
+ const [error, setError] = useState(null);
1046
+ const refresh = useCallback(async () => {
1047
+ try {
1048
+ setIsLoading(true);
1049
+ const data = await client.getTables();
1050
+ setTables(data);
1051
+ setError(null);
1052
+ } catch (err) {
1053
+ setError(err);
1054
+ } finally {
1055
+ setIsLoading(false);
1056
+ }
1057
+ }, [client]);
1058
+ useEffect(() => {
1059
+ void refresh();
1060
+ }, [refresh]);
1061
+ return { tables, isLoading, error, refresh };
1062
+ }
1063
+ function useConnection() {
1064
+ const { socket, connectionState, connect, disconnect } = usePoker();
1065
+ const [latency, setLatency] = useState(null);
1066
+ const ping = useCallback(async () => {
1067
+ if (!socket?.isConnected()) return null;
1068
+ try {
1069
+ const ms = await socket.ping();
1070
+ setLatency(ms);
1071
+ return ms;
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ }, [socket]);
1076
+ return {
1077
+ state: connectionState,
1078
+ isConnected: connectionState === "connected",
1079
+ isConnecting: connectionState === "connecting",
1080
+ isReconnecting: connectionState === "reconnecting",
1081
+ latency,
1082
+ connect,
1083
+ disconnect,
1084
+ ping
1085
+ };
1086
+ }
1087
+
1088
+ export { PokerProvider, useConnection, usePoker, usePokerClient, usePokerSocket, useTable, useTables, useUser };
1089
+ //# sourceMappingURL=index.js.map
1090
+ //# sourceMappingURL=index.js.map