import { data, redirect } from "react-router"; import type { RouterContextProvider } from "react-router"; import { NAMESPACE_COOKIE, SESSION_COOKIE, refsErrorCode, type Gate, type Problem, type Refs, type Session } from "@refs/backend/contract"; import { refsContext, requestContext } from "../context"; type Context = Readonly; const PROBLEM_STATUS: Record = { invalid: 400, conflict: 409, rate_limited: 429, unavailable: 502 }; export function readCookie(request: Request, name: string): string | null { for (const part of (request.headers.get("cookie") ?? "").split(";")) { const [key, ...value] = part.trim().split("="); if (key === name) return value.join("="); } return null; } export function sessionToken(request: Request): string | null { return readCookie(request, SESSION_COOKIE); } export function sessionCookie(session: Session): string { return `${SESSION_COOKIE}=${session.token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${session.maxAge}`; } export function namespaceCookie(slug: string): string { return `${NAMESPACE_COOKIE}=${slug}; Path=/; Secure; SameSite=Lax; Max-Age=31536000`; } export function clearedSessionCookie(): string { return `${SESSION_COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0`; } export function gate(context: Context): Gate { return context.get(requestContext).backend.gate(); } export function refs(context: Context): Refs { const handle = context.get(refsContext); if (!handle) throw new Error("The refs handle is opened by the root middleware."); return handle; } /** The handle for a signed-in actor; anonymous visitors are sent to sign in. */ export function signedIn(context: Context): Refs { const handle = refs(context); if (!handle.viewer.person) throw redirect("/login"); return handle; } /** Turns the backend's thrown failures into HTTP responses: missing things become 404s and anonymous access becomes a sign-in redirect. */ export async function found(promise: Promise): Promise { try { return await promise; } catch (error) { const code = refsErrorCode(error); if (code === "not_found") throw data(null, { status: 404 }); if (code === "sign_in_required") throw redirect("/login"); throw error; } } export function failed(problem: Problem, extra: T) { return data({ ...extra, error: problem.message }, { status: PROBLEM_STATUS[problem.code] }); } export function fullName(params: { readonly ns?: string; readonly repo?: string }): string { return `${params.ns}/${params.repo}`; } export function formText(form: FormData, name: string): string { const value = form.get(name); return typeof value === "string" ? value.trim() : ""; } export function formList(form: FormData, name: string): string[] { return form.getAll(name).filter((value): value is string => typeof value === "string"); } /** The current time in seconds, the unit every timestamp from the backend uses. */ export function nowSeconds(): number { return Math.floor(Date.now() / 1000); }