games_app/prediqo_web/src/features/candle-predict/ws/protocol.ts
2026-07-29 19:54:58 +02:00

84 lines
2.8 KiB
TypeScript

import type { GameState } from '../types';
export type WsClientMessage =
| { type: 'subscribe'; intervalMinutes: number }
| { type: 'unsubscribe'; intervalMinutes: number }
| { type: 'ping'; ts: number };
export type WsServerMessage =
| { type: 'connected'; authenticated: boolean; path: string }
| { type: 'pong'; ts: number }
| { type: 'subscribed'; intervalMinutes: number; snapshot: GameState }
| {
type: 'round.updated';
intervalMinutes: number;
round: GameState['round'];
versions?: { round?: number };
}
| {
type: 'round.settled';
intervalMinutes: number;
round: GameState['round'];
candle?: Record<string, unknown>;
versions?: { round?: number };
}
| { type: 'candle.append'; intervalMinutes: number; candle: Record<string, unknown> }
| {
type: 'bet.accepted';
bet: Record<string, unknown>;
idempotencyKey?: string;
versions?: { bet?: number; auto?: number };
}
| { type: 'bet.pending'; idempotencyKey: string }
| { type: 'bet.rejected'; idempotencyKey: string; error: string }
| {
type: 'multi.updated';
intervalMinutes: number;
userMultiBet: GameState['userMultiBet'];
versions?: { bet?: number };
}
| {
type: 'auto.updated';
autoSettings: Partial<NonNullable<GameState['autoSettings']>>;
versions?: { auto?: number };
}
| { type: 'config.updated'; intervalMinutes: number; versions?: { config?: number } }
| { type: 'error'; code: string; message: string };
export function resolveWsBaseUrl(): string {
const explicit = (import.meta.env.VITE_WS_URL as string | undefined)?.replace(/\/$/, '');
if (typeof window !== 'undefined') {
const pageHost = window.location.host;
if (explicit) {
try {
const configured = new URL(explicit);
// Use baked URL only when it targets the same host the user is browsing.
if (configured.host === pageHost) return explicit;
} catch {
/* fall through to same-origin */
}
}
// Prefer same-origin /ws/ (nginx on :9080 or :9443) so a stale build URL cannot break live updates.
const u = new URL(window.location.origin);
u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:';
u.pathname = '/ws/v1/games/candle-predict';
u.search = '';
return u.toString().replace(/\/$/, '');
}
if (explicit) return explicit;
const api = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';
const url = new URL(api);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
url.port = import.meta.env.VITE_WS_PORT || '4001';
url.pathname = '/ws/v1/games/candle-predict';
url.search = '';
return url.toString().replace(/\/$/, '');
}
export function isWsEnabled(): boolean {
return import.meta.env.VITE_WS_ENABLED === 'true';
}