Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189/** * Shared fake LRCLIB for tests — the third-party half of the network, kept out of * `test/navidrome.ts` for the same reason the audio stubs live in `test/audio.ts`: the * library server and the lyric host have nothing in common, and a test should be able * to say "the server answered and LRCLIB did not" without either fake knowing about * the other. * * Deliberately not `*.test.ts`, for the same reason as its Navidrome twin: vitest must * not collect it. * * The replies are the wire's, not the client's: a 404 carries LRCLIB's own error body, a * 429 carries a `Retry-After`, and the refusals the docs warn about are plain text. A * fake that answered with what the client wants to hear would test nothing about the * paths the client exists to handle. */import { vi } from "vitest";
/** One lyrics record, as the API spells it. */export interface FakeLyricsRecord { id: number; trackName: string; artistName: string; albumName?: string | null; duration?: number | null; instrumental?: boolean; hasWordSync?: boolean; syncedLyrics?: string | null; plainLyrics?: string | null;}
/** What the fake puts on the wire for one endpoint. */export interface FakeReply { status: number; /** the body, JSON-encoded unless `type` says otherwise */ body?: unknown; /** content type; `application/json` unless stated */ type?: string; headers?: Record<string, string>;}
export interface LrclibRoute { /** answer for one request, given the query it arrived with */ (params: URLSearchParams, asks: number): FakeReply | Promise<FakeReply>;}
export interface LrclibStub { /** the fetch stub to hand `vi.stubGlobal` / `stubStreamFetch` */ fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<unknown>; /** every lrclib URL asked, in order */ urls: string[]; /** the query of every `/api/get`, in order */ gets: URLSearchParams[]; /** the query of every `/api/search`, in order */ searches: URLSearchParams[]; /** the headers of every request, in order */ headers: Record<string, string>[]; /** how many times an endpoint was asked */ asked(endpoint: "/api/get" | "/api/search"): number;}
/** A 200 with one record — what `/api/get` answers when it has the lyric. */export const foundRecord = (record: FakeLyricsRecord): FakeReply => ({ status: 200, body: { instrumental: false, hasWordSync: false, ...record },});
/** A 200 with a list — what `/api/search` answers. */export const foundRecords = (records: FakeLyricsRecord[]): FakeReply => ({ status: 200, body: records.map((r) => ({ instrumental: false, hasWordSync: false, ...r })),});
/** * A 404, in LRCLIB's own words. * * The body is included because the client must not need it: the docs say the rate limiter's body * is not even guaranteed to be JSON, and a client that read the message from a 404 would be a * client that broke when the message was absent. */export const trackNotFound = (): FakeReply => ({ status: 404, body: { message: "Failed to find specified track", name: "TrackNotFound", statusCode: 404 },});
/** A 429 with the header the client is required to honour. */export const throttled = (retryAfter = "3"): FakeReply => ({ status: 429, body: "Too many requests", type: "text/plain", headers: { "retry-after": retryAfter },});
/** A 503, which the docs say to retry after the wait. */export const busy = (retryAfter = "1"): FakeReply => ({ status: 503, body: "The server is busy, please retry in a moment", type: "text/plain", headers: { "retry-after": retryAfter },});
/** The framework's plain-text refusal, which arrives with a 200 on a malformed query. */export const plainText = ( body = "Failed to deserialize query string: missing field `artist_name`",) => ({ status: 200, body, type: "text/plain",});
/** A 200 whose body is not a lyric at all. */export const malformed = (body: unknown = { nope: true }): FakeReply => ({ status: 200, body });
/** * The fake host. * * Everything that is not lrclib.net is handed to `base`, which is how a test keeps one fetch stub * for the whole app: the Navidrome fake answers the library, this answers the lyrics, and neither * is asked about a URL it does not own. */export function lrclibFetch( options: { /** what `/api/get` answers; a 404 by default, which is the honest "nothing here" */ get?: LrclibRoute; /** what `/api/search` answers; an empty list by default */ search?: LrclibRoute; /** everything that is not this host */ base?: (input: RequestInfo | URL, init?: RequestInit) => Promise<unknown>; /** throw instead of answering, for the tests about an outage */ down?: boolean; } = {},): LrclibStub { const urls: string[] = []; const gets: URLSearchParams[] = []; const searches: URLSearchParams[] = []; const headers: Record<string, string>[] = [];
const reply = async (url: URL, route: LrclibRoute | undefined, fallback: FakeReply) => { const params = url.searchParams; const isGet = !url.pathname.endsWith("/search"); (isGet ? gets : searches).push(params); const answer = route ? await route(params, (isGet ? gets : searches).length) : fallback; return responseOf(answer); };
const impl = async (input: RequestInfo | URL, init?: RequestInit): Promise<unknown> => { const url = String(input); if (!url.includes("lrclib.net")) { if (!options.base) throw new Error(`lrclib fake: unhandled url ${url}`); return options.base(input, init); } if (options.down) throw new TypeError("Failed to fetch"); urls.push(url); const parsed = new URL(url); const isGet = !parsed.pathname.endsWith("/search"); headers.push((init?.headers as Record<string, string> | undefined) ?? {}); return reply( parsed, isGet ? options.get : options.search, isGet ? trackNotFound() : { status: 200, body: [] }, ); };
return { fetch: vi.fn(impl), urls, gets, searches, headers, asked: (endpoint) => (endpoint === "/api/get" ? gets.length : searches.length), };}
/** A `Response` in the shape the client reads: status, headers, and a JSON body. */function responseOf(reply: FakeReply): unknown { const type = reply.type ?? "application/json"; const body = reply.body; return { ok: reply.status >= 200 && reply.status < 300, status: reply.status, headers: new Headers({ "content-type": type, ...reply.headers }), json: async () => { if (!type.includes("json")) throw new TypeError("body is not JSON"); if (body === undefined) throw new TypeError("no body"); return body; }, text: async () => (typeof body === "string" ? body : JSON.stringify(body ?? "")), };}