RotNot / src /lib /lichess.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
5.25 kB
/**
* Lichess API client
*
* Docs: https://lichess.org/api
* Token: set LICHESS_API_TOKEN in .env (optional — public endpoints work without it)
*/
const LICHESS_BASE = "https://lichess.org";
function lichessHeaders(): HeadersInit {
const token = process.env.LICHESS_API_TOKEN;
return {
Accept: "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
// --------------------------------------------------------------------------
// Puzzle types
// --------------------------------------------------------------------------
export interface LichessPuzzleGame {
id: string;
perf: { key: string; name: string };
rated: boolean;
players: { name: string; id: string; color: string }[];
pgn: string;
clock: string;
}
export interface LichessPuzzleData {
id: string;
rating: number;
plays: number;
solution: string[];
themes: string[];
}
export interface LichessPuzzleResponse {
game: LichessPuzzleGame;
puzzle: LichessPuzzleData;
}
// --------------------------------------------------------------------------
// getLichessPuzzle
// --------------------------------------------------------------------------
/**
* Fetches the next Lichess puzzle (daily or personalised if token supplied).
* Returns null on fetch/parse errors so callers can fall back gracefully.
*/
export async function getLichessPuzzle(): Promise<LichessPuzzleResponse | null> {
try {
const res = await fetch(`${LICHESS_BASE}/api/puzzle/next`, {
headers: lichessHeaders(),
next: { revalidate: 0 }, // always fresh
});
if (!res.ok) {
console.error(`Lichess puzzle fetch failed: ${res.status} ${res.statusText}`);
return null;
}
return (await res.json()) as LichessPuzzleResponse;
} catch (err) {
console.error("getLichessPuzzle error:", err);
return null;
}
}
// --------------------------------------------------------------------------
// getLichessDailyPuzzle
// --------------------------------------------------------------------------
/**
* Fetches today's Lichess daily puzzle (no auth required).
*/
export async function getLichessDailyPuzzle(): Promise<LichessPuzzleResponse | null> {
try {
const res = await fetch(`${LICHESS_BASE}/api/puzzle/daily`, {
headers: { Accept: "application/json" },
next: { revalidate: 3600 }, // cache for 1 hour
});
if (!res.ok) {
console.error(`Lichess daily puzzle fetch failed: ${res.status} ${res.statusText}`);
return null;
}
return (await res.json()) as LichessPuzzleResponse;
} catch (err) {
console.error("getLichessDailyPuzzle error:", err);
return null;
}
}
// --------------------------------------------------------------------------
// challengeStockfish
// --------------------------------------------------------------------------
export interface StockfishChallenge {
id: string;
url: string;
}
/**
* Creates a Stockfish bot challenge on Lichess.
* Requires a valid LICHESS_API_TOKEN.
* level: 1 (easiest) → 8 (strongest)
*/
export async function challengeStockfish(
level: number = 4,
): Promise<StockfishChallenge | null> {
const token = process.env.LICHESS_API_TOKEN;
if (!token) {
console.error("challengeStockfish: LICHESS_API_TOKEN not set");
return null;
}
const clampedLevel = Math.max(1, Math.min(8, level));
const body = new URLSearchParams({
level: String(clampedLevel),
clock: JSON.stringify({ limit: 300, increment: 3 }),
color: "random",
variant: "standard",
});
try {
const res = await fetch(`${LICHESS_BASE}/api/challenge/stockfish`, {
method: "POST",
headers: {
...lichessHeaders(),
"Content-Type": "application/x-www-form-urlencoded",
},
body: body.toString(),
});
if (!res.ok) {
const text = await res.text();
console.error(`challengeStockfish failed: ${res.status} ${text}`);
return null;
}
const data = (await res.json()) as { id: string };
return {
id: data.id,
url: `${LICHESS_BASE}/${data.id}`,
};
} catch (err) {
console.error("challengeStockfish error:", err);
return null;
}
}
// --------------------------------------------------------------------------
// getGameStream (NDJSON event stream)
// --------------------------------------------------------------------------
/**
* Returns a ReadableStream of NDJSON game events for the given Lichess game ID.
* The caller is responsible for reading and parsing lines.
* Requires LICHESS_API_TOKEN.
*/
export async function getGameStream(gameId: string): Promise<ReadableStream<Uint8Array> | null> {
const token = process.env.LICHESS_API_TOKEN;
if (!token) {
console.error("getGameStream: LICHESS_API_TOKEN not set");
return null;
}
try {
const res = await fetch(`${LICHESS_BASE}/api/board/game/stream/${gameId}`, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/x-ndjson",
},
});
if (!res.ok || !res.body) {
console.error(`getGameStream failed: ${res.status}`);
return null;
}
return res.body;
} catch (err) {
console.error("getGameStream error:", err);
return null;
}
}