import type { MatchCommandEnvelope, MatchCommandResult, MatchEvent, PlayerMatchView, PublicMatchView, } from "@instlang/economancy-protocol"; export interface CreateMatchResponse { readonly view: PublicMatchView; readonly player: string; readonly inviteToken: string; readonly hostToken: string; readonly seatToken: string; } export interface JoinMatchResponse { readonly matchId: string; readonly player: string; readonly seatToken: string; readonly view: PlayerMatchView; } export class EconomancyApi { private seatToken = ""; private hostToken = ""; public constructor(private readonly baseUrl: string) {} public setCredentials(seatToken: string, hostToken: string): void { this.seatToken = seatToken; this.hostToken = hostToken; } public async createMatch(matchId: string, players: readonly string[], player: string): Promise { return this.request("/matches", { method: "POST", body: { matchId, players, player }, }); } public async joinMatch(matchId: string, player: string, inviteToken: string): Promise { return this.request(`/matches/${encodeURIComponent(matchId)}/join`, { method: "POST", body: { player, inviteToken }, }); } public async getPlayerView(matchId: string): Promise { const response = await this.request<{ readonly view: PlayerMatchView }>( `/matches/${encodeURIComponent(matchId)}`, {}, this.seatToken, ); return response.view; } public async dispatch(matchId: string, envelope: MatchCommandEnvelope): Promise { const token = envelope.command.kind === "advance_income" ? this.hostToken : this.seatToken; return this.request(`/matches/${encodeURIComponent(matchId)}/commands`, { method: "POST", body: envelope, }, token); } public async getEvents(matchId: string, sequenceExclusive = -1): Promise { const response = await this.request<{ readonly events: readonly MatchEvent[] }>(`/matches/${encodeURIComponent(matchId)}/events?since=${sequenceExclusive}`); return response.events; } private async request(path: string, options: { readonly method?: string; readonly body?: unknown } = {}, token?: string): Promise { const init: RequestInit = { method: options.method ?? "GET", }; const headers: Record = {}; if (options.body !== undefined) { headers["content-type"] = "application/json"; init.body = JSON.stringify(options.body); } if (token !== undefined && token !== "") headers.authorization = `Bearer ${token}`; if (Object.keys(headers).length > 0) init.headers = headers; const response = await fetch(`${this.baseUrl.replace(/\/$/, "")}${path}`, init); const body = await response.json() as unknown; if (!response.ok) { const error = isRecord(body) && typeof body.error === "string" ? body.error : `http_${response.status}`; throw new Error(error); } return body as T; } } function isRecord(value: unknown): value is Readonly> { return value !== null && typeof value === "object" && !Array.isArray(value); }