chadtmiller.com/knotless

Git hosted in your atproto account, on any stock PDS, fast enough for agents.

git clone knotless://chadtmiller.com/knotless

needs the knotless git helper. set it up

main
38 lines · 1.3 KB Raw History
// 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<string, string>) => 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<T>(
	{ fetch, setHeaders, url }: Load,
	path?: string,
	missing = false
): Promise<T> {
	// 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();
}