Spaces:
Sleeping
Sleeping
File size: 5,800 Bytes
9f0c00b 93ae949 f5af762 9f0c00b 93ae949 67057ab 93ae949 9f0c00b f5af762 9f0c00b f5af762 9f0c00b 1302ebc 758be85 1302ebc 2545230 1302ebc 3443892 1302ebc 758be85 67057ab 1302ebc f5af762 1302ebc f5af762 1302ebc f5af762 1302ebc f5af762 1302ebc 76e92fa 93ae949 f5af762 1302ebc 93ae949 1302ebc 76e92fa 1302ebc 93ae949 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | /** 鬼影 REST 前端 client(模式 A,04 §5)。dev 經 Vite proxy 轉到後端 :3001。 */
import type { Action, Campaign, ClassType, GhostRecord } from "@wcg/battle-core";
import { apiFetch } from "./apiClient.js"; // 統一收斂:Activity 帶 Bearer、網頁版走同源 cookie
export type RunKind = "single" | "pvp" | "pve";
/**
* 單場紀錄(供「遊玩紀錄」彈窗)。單人=該場摘要欄位;pvp/pve=勝負+對手/Boss 名(單人專屬欄位省略)。
* kind 省略=單人(相容舊資料)。
*/
export interface RunRecord {
at: string;
kind?: RunKind;
classType: ClassType;
cleared: boolean; // 單人=破關;pvp=勝;pve=Boss 被擊敗
// 單人專屬
campaign?: Campaign;
hardMode?: boolean;
extreme?: boolean; // 極難(insane);隱含 hardMode
reachedStage?: number;
peakAtk?: number;
peakDef?: number;
turns?: number;
outcome?: "VICTORY" | "GAME_OVER";
// 連線專屬
enemyName?: string; // pvp="對手";pve=Boss 名
}
/** 連線(pvp/pve)戰績回報:後端無法重播,直接採信此結果(個人統計、非排行榜)。 */
export interface OnlineRunReport {
kind: "pvp" | "pve";
classType: ClassType;
cleared: boolean;
enemyName: string;
}
export async function uploadGhost(record: GhostRecord): Promise<{ id: string; verified: boolean }> {
const res = await apiFetch("/api/ghosts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(record),
});
if (!res.ok) throw new Error(`upload failed: ${res.status}`);
return res.json();
}
export async function fetchRandomGhost(): Promise<GhostRecord | null> {
const res = await apiFetch("/api/ghosts/random");
if (res.status === 204) return null;
if (!res.ok) throw new Error(`fetch failed: ${res.status}`);
return res.json();
}
// ===== 帳號 / 個人統計(同源 fetch,session cookie 自動帶) =====
export interface UserStats {
plays: number;
clears: number;
peakAtk: number;
peakDef: number;
maxReachedStage: number;
/** 各「敵人×難度」最高到達 Stage。key:`slime`/`slime:hard`/`sanctus`/`sanctus:hard`。 */
maxStageByMode?: Record<string, number>;
totalTurns: number;
classPlays: Partial<Record<ClassType, number>>;
recentClasses: ClassType[];
lastPlayedAt?: string;
runs?: RunRecord[]; // 最近 N 場逐場紀錄(舊→新)
}
export interface PublicUser {
id: string;
displayName: string;
provider: string;
stats: UserStats;
}
/** 單場戰績回報:只送 seed+動作序列+該場設定,後端權威重播算統計。 */
export interface RunReportPayload {
seed: number;
actions: Action[];
classType: ClassType;
campaign: Campaign;
maxLevel: number;
hardMode?: boolean; // 困難模式:後端權威重播須一致(困難會多消費 rng),也用於分難度統計
extreme?: boolean; // 極難(insane):重播須帶;且須附自組牌組
deckOverride?: number[]; // 極難自組 30 張牌(重播洗牌須一致)
ruleVersion: string;
cardsHash: string;
}
/** 列出後端已啟用的 OAuth provider(如 ["discord","google"]);失敗回空陣列。 */
export async function fetchProviders(): Promise<string[]> {
try {
const res = await apiFetch("/api/auth/providers");
if (!res.ok) return [];
const j = await res.json();
return Array.isArray(j.providers) ? j.providers : [];
} catch {
return [];
}
}
/** 取自己的資料(含統計);未登入 → null。 */
export async function fetchMe(): Promise<PublicUser | null> {
const res = await apiFetch("/api/me");
if (res.status === 401 || res.status === 404) return null; // 未登入 / 後端未啟用帳號
if (!res.ok) throw new Error(`me failed: ${res.status}`);
return res.json();
}
export async function logout(): Promise<void> {
await apiFetch("/api/auth/logout", { method: "POST" });
}
/** dev 環境免 OAuth 登入(後端僅非 production 開放);失敗(如 production 關閉)回 null。 */
export async function devLogin(username: string): Promise<PublicUser | null> {
const res = await apiFetch("/api/auth/dev-login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username }),
});
if (!res.ok) return null;
return res.json();
}
export type ReportResult =
| { stats: UserStats }
| { status: "version-mismatch" }
| { status: "rejected"; httpStatus: number; reason?: string } // 422/429/500…:這場未計入,讓 UI 能提示而非靜默
| null;
async function postRun(body: RunReportPayload | OnlineRunReport): Promise<ReportResult> {
const res = await apiFetch("/api/me/runs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.status === 401) return null; // 未登入 / 登入過期
if (res.status === 409) return { status: "version-mismatch" }; // 規則版本不符 → 這場不被採計
if (!res.ok) {
// 422 invalid-run / 429 rate-limited / 500 …:取出後端 reason(若有),不再 throw 被靜默吞掉。
let reason: string | undefined;
try { reason = ((await res.json()) as { reason?: string; error?: string }).reason; } catch { /* 無 JSON body */ }
return { status: "rejected", httpStatus: res.status, reason };
}
return res.json();
}
/** 回報一場單人戰績(後端權威重播算統計)。未登入 → null。 */
export async function reportRun(payload: RunReportPayload): Promise<ReportResult> {
return postRun(payload);
}
/** 回報一場連線(pvp/pve)戰績(後端直接採信)。未登入 → null。 */
export async function reportOnlineRun(payload: OnlineRunReport): Promise<ReportResult> {
return postRun(payload);
}
|