| |
| |
| |
| |
|
|
| import { Client } from '@gradio/client'; |
|
|
| export function sessionId() { |
| let sid = sessionStorage.getItem('mlp_session_id'); |
| if (!sid) { |
| sid = `web-${Math.random().toString(36).slice(2, 10)}-${Date.now().toString(36)}`; |
| sessionStorage.setItem('mlp_session_id', sid); |
| } |
| return sid; |
| } |
|
|
| export class ApiError extends Error { |
| constructor(status, message) { |
| super(message); |
| this.status = status; |
| } |
| } |
|
|
| |
| |
| let _clientPromise = null; |
| function client() { |
| if (!_clientPromise) { |
| _clientPromise = Client.connect(window.location.origin).catch((e) => { |
| _clientPromise = null; |
| throw new ApiError(0, e?.message || 'could not connect to the game server'); |
| }); |
| } |
| return _clientPromise; |
| } |
|
|
| async function call(endpoint, args) { |
| const app = await client(); |
| const res = await app.predict(endpoint, args); |
| return res?.data?.[0]; |
| } |
|
|
| |
| export async function turn(body) { |
| const d = await call('/turn', { payload: body, sid: sessionId() }); |
| if (d && typeof d === 'object' && d.error && !('round' in d)) { |
| throw new ApiError(d.rejected ? 409 : 400, d.error); |
| } |
| return d; |
| } |
|
|
| |
| export async function gameModel(body) { |
| return call('/game_model', { payload: body || {}, sid: sessionId() }); |
| } |
|
|
| |
| export async function announce(round) { |
| return call('/announce', { sid: sessionId(), round }); |
| } |
|
|