// What a page shows, read from knotless-serve. import { error, redirect } from '@sveltejs/kit'; import type { Failure } from '#lib/api/Failure.ts'; type Load = { fetch: typeof fetch; setHeaders: (headers: Record) => void; url: URL; }; /** * The answer at `path`, for this page: `/_data` and the page's own path * if it names none. The page is cached as the answer is; a repository * renamed sends it on to the same page under the new name; and a failure * is the page's, but for a 404 when the page can do `missing` it. */ export async function data( { fetch, setHeaders, url }: Load, path?: string, missing = false ): Promise { // Asked again each time, past an answer a browser kept from when answers // at a commit hash were sent as immutable. const res = await fetch(path ?? `/_data${url.pathname}${url.search}`, { cache: 'no-cache' }); if (res.redirected) { const to = new URL(res.url); redirect(307, `${to.pathname.replace(/^\/_data/, '')}${to.search}`); } if (res.status === 404 && missing) return null as T; if (!res.ok) { const failure: Failure | null = await res.json().catch(() => null); error(res.status, failure?.message ?? res.statusText); } const cache = res.headers.get('cache-control'); if (cache) setHeaders({ 'cache-control': cache }); return res.json(); }